COPA2 Ndsem TT

Download as pdf or txt
Download as pdf or txt
You are on page 1of 246

COMPUTER OPERATOR AND

PROGRAMMING ASSISTANT
NSQF LEVEL - 4

1st Year (Volume II of II)

TRADE THEORY

SECTOR: IT & ITES

DIRECTORATE GENERAL OF TRAINING


MINISTRY OF SKILL DEVELOPMENT & ENTREPRENEURSHIP
GOVERNMENT OF INDIA

NATIONAL INSTRUCTIONAL
MEDIA INSTITUTE, CHENNAI
Post Box No. 3142, CTI Campus, Guindy, Chennai - 600 032
(i)

Copyright Free under CC BY Licence


Sector : IT & ITES
Duration : 1 - Year
Trade : Computer Operator and Programming Assistant 1st Year (Volume II of II) - Trade Theory -
NSQF Level 4

First Edition : November 2018 Copies : 1,000


First Reprint : January 2019 Copies : 2,000

Rs. 245/-

All rights reserved.

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)

Copyright Free under CC BY Licence


FOREWORD

The Government of India has set an ambitious target of imparting skills to 30 crores people, one out of every
four Indians, by 2020 to help them secure jobs as part of the National Skills Development Policy. Industrial
Training Institutes (ITIs) play a vital role in this process especially in terms of providing skilled manpower.
Keeping this in mind, and for providing the current industry relevant skill training to Trainees, ITI syllabus
has been recently updated with the help of Mentor Councils comprising various stakeholder's viz. Industries,
Entrepreneurs, Academicians and representatives from ITIs.

The National Instructional Media Institute (NIMI), Chennai, has now come up with instructional material to
suit the revised curriculum for Computer Operator and Programming Assistant Trade Theory 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.

New Delhi - 110 001

(iii)

Copyright Free under CC BY Licence


PREFACE

The National Instructional Media Institute (NIMI) was established in 1986 at Chennai by then Directorate
General of Employment and Training (D.G.E & T), Ministry of Labour and Employment, (now under Directorate
General of Training, Ministry of Skill Development and Entrepreneurship) Government of India, with technical
assistance from the Govt. of the Federal Republic of Germany. The prime objective of this institute is to
develop and provide instructional materials for various trades as per the prescribed syllabi (NSQF Level 4)
under the Craftsman and Apprenticeship Training Schemes.

The instructional materials are created keeping in mind, the main objective of Vocational Training under
NCVT/NAC in India, which is to help an individual to master skills to do a job. The instructional materials are
generated in the form of Instructional Media Packages (IMPs). An IMP consists of Theory book, Practical
book, Test and Assignment book, Instructor Guide, Audio Visual Aid (Wall charts and Transparencies) and
other support materials.

The trade practical book consists of series of exercises to be completed by the trainees in the workshop.
These exercises are designed to ensure that all the skills in the prescribed syllabus are covered. The trade
theory book provides related theoretical knowledge required to enable the trainee to do a job. The test and
assignments will enable the instructor to give assignments for the evaluation of the performance of a trainee.
The wall charts and transparencies are unique, as they not only help the instructor to effectively present a
topic but also help him to assess the trainee's understanding. The instructor guide enables the instructor to
plan his schedule of instruction, plan the raw material requirements, day to day lessons and demonstrations.

IMPs also deals with the complex skills required to be developed for effective team work. Necessary care
has also been taken to include important skill areas of allied trades as prescribed in the syllabus.

The availability of a complete Instructional Media Package in an institute helps both the trainer and
management to impart effective training.

The IMPs are the outcome of collective efforts of the staff members of NIMI and the members of the Media
Development Committees specially drawn from Public and Private sector industries, various training institutes
under the Directorate General of Training (DGT), Government and Private ITIs.

NIMI would like to take this opportunity to convey sincere thanks to the Directors of Employment & Training
of various State Governments, Training Departments of Industries both in the Public and Private sectors,
Officers of DGT and DGT field institutes, proof readers, individual media developers and coordinators, but for
whose active support NIMI would not have been able to bring out this materials.

R. P. DHINGRA
Chennai - 600 032 EXECUTIVE DIRECTOR

(iv)

Copyright Free under CC BY Licence


ACKNOWLEDGEMENT

National Instructional Media Institute (NIMI) sincerely acknowledges with thanks for the co-operation and
contribution extended by the following Media Developers and their sponsoring organisations to bring out this
Instructional Material (Trade Theory) for the trade of Computer Operator and Programming Assistant under
the IT & ITES Sector

MEDIA DEVELOPMENT COMMITTEE MEMBERS

Shri. M. K. Sunil _ Training Officer


NSTI, Chennai
Tamil Nadu

Shri. C.Jeyaprakash _ Technical Head


Cadd Cae Industrial School, Dindigul
Tamil Nadu

Shri. S.Venkadesh Babu _ Chief Executive Officer,


NSree Media Technologies, Dindigul
Tamil Nadu

Smt. R. Jeyalakshmi _ Assistant Training officer,


Govt. ITI (W), Coimbatore
Tamil Nadu

Shri. K. Kumaravel _ Assistant Training Officer,


Govt. ITI, Central Prison Campus, Trichy
Tamil Nadu

Shri. J. Malarkodi _ Assistant Training Officer,


Govt. ITI., Salem
Tamil Nadu

Shri. J. Herman _ Assitant Manager,


Co-ordinator, NIMI,
Chennai - 32

NIMI records its appreciation for the Data Entry, CAD, DTP operators for their excellent and devoted services in
the process of development of this Instructional Material.

NIMI also acknowledges with thanks the invaluable efforts rendered by all other NIMI staff who have contributed
towards the development of this Instructional Material.

NIMI is also grateful to everyone who has directly or indirectly helped in developing this Instructional Material.

(v)

Copyright Free under CC BY Licence


INTRODUCTION
TRADE THEORY

The manual of trade theory consists of theorectical information for the Second Semester course of the COPA
Trade. The contents are sequenced according to the practical exercise contained in the manual on Trade
practical. Attempt has been made to relate the theortical aspects with the skill covered in each exercise to the
extent possible. This co-relation is maintained to help the trainees to develop the perceptional capabilities for
performing the skills.

The Trade Theory has to be taught and learnt along with the corresponding exercise contained in the manual
on trade practical. The indicating about the corresponding practical exercise are given in every sheet of this
manual.

It will be preferable to teach/learn the trade theory connected to each exercise atleast one class before
performing the related skills in the system lab. The trade theory is to be treated as an integrated part of each
exercise.

The material is not the purpose of self learning and should be considered as supplementary to class room
instruction.

TRADE PRACTICAL

The trade practical manual is intented to be used in workshop . It consists of a series of practical exercies to
be completed by the trainees during the Second Semester course of the COPA trade supplemented and
supported by instructions/ informations to assist in performing the exercises. These exercises are designed
to ensure that all the skills in the prescribed syllabus are covered.

The manual is divided into five modules to maintain completancy of learning process in a stipulated time basis.

The skill training in the computer lab is planned through a series of practical exercises centred around some
practical project. However, there are few instance where the individual exercise does not form a part of project.

While developing the practical manual a sincere effort was made to prepare each exercise which will be easy
to understand and carry out even by below average traninee. However the development team accept that there
if a scope for further improvement. NIMI, looks forward to the suggestions from the experienced training faculty
for improving the manual.

(vi)

Copyright Free under CC BY Licence


CONTENTS

Lesson No. Title of the Lesson Page No.

Module 1 : JavaScript and creating Web page

2.1.94 Understanding JavaScript 1

2.1.95 Introduction to Web servers and External JavaScript files 4

2.1.96A Using JavaScript Variable and data types 6

2.1.96B Using JavaScript Constants and Operators 10

2.1.97A & Control statements, Loops and Popup boxes in JavaScript 14


2.1.97B

2.1.98A & Error handling in JavaScript 20


2.1.98B

2.1.99 Arrays in JavaScript 23

2.1.100A Introduction to Function in JavaScript 29

2.1.100B Objects in JavaScript 31

2.1.101A String and number methods in JavaScript 36

2.1.101B Math objects in JavaScript 42

2.1.101C JavaScript Dates 44

2.1.102A Document Object Model and Open source software 52

2.1.102B Develop and edit web pages in KompoZer 61

2.1.102C Concepts of Animation and Multimedia files in JavaScript 70

2.1.103A & Introduction to IIS and XAMPP, Dynamic Website and


2.1.103B Hosting and FTP tool Filezilla - Projects in JavaScript 73

Module 2 : Programming with VBA

2.2.104 Introduction to VBA features and applications 78

2.2.105A - Form Controls and Properties in VBA 83


2.2.105D

2.2.106A & Workbook and worksheet objects 87


2.2.106B

2.2.107A VBA Data types, Variables and Constants 90

2.2.107B Operators in VBA and operator precedence 94

2.2.108 VBA Message boxes and Input boxes 97

(vii)

Copyright Free under CC BY Licence


Lesson No. Title of the Lesson Page No.

2.2.109A & Decision making statements in VBA 101


2.2.109C

2.2.110A & Looping statements in VBA 105


2.2.110B

2.2.111A & Arrays in VBA 108


2.2.111C

2.2.112 String manipulation in VBA 111

2.2.113 Built in Functions in VBA 115

2.2.114& User defined functions in VBA 119


2.2.115

2.2.116 Create and Edit Macros 125

2.2.117 User forms and control in Excel VBA 126

2.2.118 Methods and Events in VBA 129

2.2.119 Debugging Techniques in VBA 131

2.2.120 Object Oriented Programming concepts, Concepts of classes, 135


Objects, properties and Methods

Module 3 : Using Accounting Software

2.3.121 Introduction to Tally, Features and Advantages 143

2.3.122 Implementing Accounts in Tally - Basics of Accounting, 146


Golden Rules of Accounting, Voucher Entry, Ledger Posting,
Final Accounts Preparation

2.3.123 Financial Accounting Reports 160

2.3.124 Costing Systems 168

2.3.125 & Budgeting systems, Scenario management and 172


2.3.126 Variance analysis

2.3.127 & Concepts of Ratios, Analysis of financial statements 175


2.3.128

2.3.129 Tax processing in Tally 178

2.3.130 Utilities 183

2.3.131 Creating Users, Backup and restore 186

2.3.132 Multilingual capability in Tally 188

(viii)

Copyright Free under CC BY Licence


Lesson No. Title of the Lesson Page No.

Module 4 : E Commerce

2.4.133 E commerce scope and benefits 189

2.4.134 Buidling Business on the Net 193

2.4.135 E Commerce Security issues and Payment Gateways 194

Module 5 : Cyber Security

2.5.136 Overview of information security and threats 196

2.5.137 Overview of security threats 201

2.5.138 Information security vulnerabilities and Risk Management 206

2.5.139 Directory services 214

2.5.140 Ac cess Control, Audit and testing 218

2.5.141 Privacy Protection and IT Act 228

LEARNING / ASSESSABLE OUTCOME

On completion of this book you shall be able to

• Develop web pages using JavaScript.

• Develop simple spread sheets by embedding VBA.

• Maintain accounts using Accounting Software

• Browse, select and transact using E-Commerce websites.

• Secure information from Internet by using Cyber Security


concept.

(ix)

Copyright Free under CC BY Licence


1st Year (Volume II of II) 06 Months

Week Learning Professional Skills Professional Knowledge


No. Outcome (Trade Practical) (Trade Theory)
With indicative hours Introduction to JavaScript

27 - 33 Develop web JavaScript & creating Web page • Introduction to Programming


pages using 94. Practice with basic elements of and Scripting Languages.
JavaScript. JavaScript. (12 Hrs) • Introduction to JavaScript
95. Embed JavaScript in HTML to and its application for the web.
display information in web • Introduction to Web
pages, documentation and Servers and their features.
formatting of HTML source • JavaScript Basics – Data
code. (18 Hrs)
types, Variables, Constants
96. Use JavaScript Variables, Data
and Conversion between
types, Constants and
data types.
Operators. (18 Hrs)
97. Use Control statements and
• Arithmetic, Comparison,
Loops in JavaScript. (18 Hrs) Logical Operators in
98. Practice with switch case, loop JavaScript. Operator
controls and Errors in precedence.
JavaScript. (18 Hrs) • Program Control
99. Practice with Arrays in Statements and loops in
JavaScript page. (12 Hrs) JavaScript.
100.Practice with functions in • Arrays in JavaScript –
JavaScript web page. (18 Hrs) concepts, types and usage.
101. Practice with String, Math and • The String data type in
Date functions in JavaScript. JavaScript. Introduction to
(24 Hrs) String, Math and Date.
102. Use online tool or open • Introduction to Functions
source software to develop and
in JavaScript.
edit web pages containing
Titles, different font sizes and
• Built in JavaScript functions
colours, frames, lists, tables, overview.
images, image map, controls, • Concepts of Pop Up boxes
CSS, forms, hyperlinks etc., use in JavaScript.
web template to create a • Introduction to the
web page of various styles. (36 Document Object Model.
Hrs) • Concepts of using
103. Develop a simple web project Animation and multimedia
using HTML, JavaScript and host files in Java Script.
it in IIS and a registered domain.
(36 Hrs)

34 - 41 Develop Programming with VBA Introduction to VBA, Features


simple spread 104. Practice with basic functions of VBA and Applications.
sheets by Editor. (3 Hrs) • Introduction to VBA features and
embedding 105. Use form controls like buttons, applications.
VBA. Check boxes, Labels, Combo Box, • Properties, events and methods
Group Box, List Box, Option Button, associated with the Button,
Scroll Bar and Spin button. (12 Hrs) Check Box, Label, Combo Box,
106.Modify object properties in V B A Group Box, Option Button, List
program. (6 Hrs) Box, Scroll Bar and Spin button
107. Write simple programs involving VBA controls.
Data types, Variables, Operators and
• VBA Data types, Variables
Constants. (18 Hrs)
and Constants.
108.Create Message boxes and I n p u t

Copyright Free under CC BY Licence


boxes in VBA. (6 Hrs) • Operators in VBA and operator
109. Work with conditional precedence.
statements like if, Else-if, and • Mathematical Expressions
Select. (12 Hrs) in VBA.
110. Practice with Loop, Loop Control
and Case statements in VBA. (15
• Introduction to Arrays in
Hrs) VBA.
111. Create and Manipulate Arrays in • Introduction to Strings in
VBA. (12 Hrs) VBA.
112. Practice with string variables in • Conditional processing in
VBA programming. (12 Hrs) VBA, using the IF, Else-if,
113. Write programs involving Select Case Statements.
Mathematical, Conversion, Date • Introduction to Loops in
and String Functions in VBA. (18 VBA.
Hrs) • VBA message boxes and
114. Create Functions, Procedures, input boxes.
Passing Parameters and Using
Returned Data. (12 Hrs)
• Introduction to Creating
115. Practice with built in functions in functions and Procedures
VBA programs. (12 Hrs) in VBA.
116. Create and edit macros. • Using the built in
(12 Hrs) functions.
117. Write code to work with Excel • Introduction to Object
in VBA forms. (12 Hrs) Oriented Programming
118. Practice with methods and Concepts. Concepts of
events in VBA Programming. Classes, Objects,
(24 Hrs) Properties and Methods.
119. Debug, Step through code, • The user forms and
Breakpoints, find and fix errors control in Excel VBA.
while debugging. (18 Hrs) • Introduction to Debugging
120. Develop a simple project Techniques.
involving MS excel and VBA.
(36 Hrs)

42 - 45 Maintain Using Accounting Software Using Accounting Software


accounts using 121. Practice Basic accounting with • Basics of Accounting,
accounting tally interface. (12 Hrs) Golden Rules of
software. 122. Create Company, Account and Accounting, Voucher
Voucher entry in Tally. (12 Hrs) Entry, Ledger Posting,
123. Generate reports for Invoice, Bill, Final Accounts
Profit & Loss account etc. (10 Hrs) Preparation.
124. Perform Cost Centre & Cost • Cash Book. Ratio Analysis,
Category management. (12 Hrs) Depreciation, Stock
125. Create and manage budgeting Management.
systems. (12 Hrs) • Analysis of VAT, Cash
126. Create Scenario and Variance
Flow, Fund Flow
Analysis. (8 Hrs)
Accounting.
127. Use Tally for Costing, Ratio
Analysis, Cash flow and Funds
• Introduction to Tally,
flow statements. (12 Hrs) features and Advantages.
128. Analyze and Manage Inventory • Implementing accounts in
control. (10 Hrs) Tally.
129. Perform Point of Sales and • Double entry system of
Taxation (VAT, Excise, Service book keeping.
Tax). (8 Hrs) • Budgeting Systems,
130. Perform System Administration Scenario management
and use other Utilities. (8 Hrs) and Variance Analysis.
131. Create users, take Backup &

Copyright Free under CC BY Licence


Restore of Company. (8 Hrs)
132. Use Multilingual Functionality in
Tally. (8 Hrs)

46 Browse, select E Commerce E Commerce Concepts


and transact 133. Browse E-commerce websites viz.
• Introduction to ECommerce
using Ecommerce ebay, Amazon, flipkart, OLX, quikr
advantages.
websites etc. and prepare comparative
statement of the main features of • Building business on
Secure
these sites. (8 Hrs) the net.
information
from Internet 134.Upload products for selling in • Payment and Order
by using cyber ECommerce Sites and make online Processing,
security purchase from E Commerce Authorization,
concept. sites.(14 Hrs) Chargeback and other
135. Manage security issues in payment methods.
ECommerce and payment • Security issues and
operations. (8 Hrs) payment gateways. and

47 Cyber Security: Cyber Security:


136. Protect information, computers • Overview of Information
and networks from viruses, Security, SSL, HTTPS,
spyware and other malicious Security threats,
code. (3 Hrs) information Security
137. Provide firewall security for vulnerability and Risk
Internet connection and management.
Network System. (6 Hrs) • Introduction to Directory
138. Protect the computer against Services, Access Control,
various internet threats. (3 Hrs) Security, Privacy
139.Make backup copies of protection, Audit and
important file, data and Security.
information. (3 Hrs) • Introduction to IT Act and
140. Secure your Wi-Fi networks penalties for cyber
using password, WEP, WPA- crimes.
PSK, WPA2-PSK, SSID, MAC
address filtering. Create
individual user accounts for
each member. (9 Hrs)
141. Limit member access to data
and information, and restrict
authority to install unnecessary
downloads. (6 Hrs)

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

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.94
COPA - JavaScript and creating Web page

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.

A script or scripting language is a computer language


with a series of commands within a file that is capable of
being executed without being compiled. Good examples
of server-side scripting languages include Perl, PHP, and
Python. The best example of a client side scripting
language is JavaScript.

Advantages of scripts Client - Javascript Server

• Open source, allowing users to view and edit the script


JavaScript History
if needed.
• Does not require the file to be compiled, but may be JavaScript was developed by Brendan Eich in 1995, which
when necessary. appeared in Netscape, a popular browser of that time.The
language was initially called Live Script and was later
• Easy to learn and write. renamed JavaScript. There are many programmers who
think that JavaScript and Java are the same. In fact,
• Easy to port between different operating systems. JavaScript and Java are very much unrelated. Java
is a very complex programming language whereas
• Much faster to develop than an actual program - some
JavaScript is only a scripting language. The syntax of
individuals and companies write scripts as a prototype
Java Script is mostly influenced by the programming
for actual programs. language C.
Disadvantages of scripts How to Run JavaScript?
• Open source, allows others to view source code, which Being a scripting language, JavaScript cannot run on
may be prohibited by some companies. its own. In fact, the browser is responsible for running
• Requires the user to install an interpreter or separate JavaScript code. When a user requests an HTML page
program before the script can be run. with JavaScript in it, the script is sent to the browser and
it is up to the browser to execute it. The main advantage
• In some situations, they may be slower than a compiled of JavaScript is that all modern web browsers support
program. JavaScript. So, you do not have to worry about whether
your site visitor uses Internet Explorer, Google Chrome,
What is Java Script?
Firefox or any other browser. JavaScript will be supported.
Also, JavaScript runs on any operating system including
JavaScript is a very powerful client-side scripting
Windows, Linux or Mac.
language. JavaScript is used mainly for enhancing the
interaction of a user with the webpage (Fig 1). In other

Copyright Free under CC BY Licence


Tools You Need to run JavaScript • It is object based language as it provides predefined
objects.
To start with, a text editor to write the code and a browser
• Every statement in JavaScript must be terminated with
to display the web pages. A text editor uses of choice
semicolon (;).
including Notepad++, Visual Studio Code, Sublime Text,
Atom or any other text editor is comfortable with. And • Most of the JavaScript control statements syntax is
also, can use any web browser including Google Chrome, same as syntax of control statements in C language.
Firefox, Microsoft Edge, Internet Explorer etc.
• An important part of JavaScript is the ability to create
new functions within scripts.
Sample JavaScript program
Advantages of JavaScript
<html>
<head> • Executed on the client side: For example, user can
validate any user input before sending a request to the
<title>My First JavaScript code!!!</title>
server. This makes less load on the server.
<script type=”text/javascript”>
• Relatively an easy language: This is quite easy to learn
alert(“Welcome to JavaScript Program!”); and the syntax that is close to English.
</script> • Instance response to the visitors: Without any server
interaction, don’t have to wait for a page reload to get
</head>
the desire result.
<body>
• Fast to the end user: As the script is executed on the
</body> user’s computer, depending on task, the results are
</html> completed almost instantly.
• Interactivity increased: Creating interfaces that can react
Features of JavaScript when the user hovers over them or activates them using
the keyboard.
JavaScript is a client side technology, it is mainly used for
client side validation, but it has lot of features which are • Rich interfaces: Drag and drop components or slider
shown in Fig 2. may give a rich interface to site visitors.

Disadvantages of JavaScript
Fig 2
  Object‐based scripting language  • Security issues: Any JavaScript snippets, while
appended onto web pages on client side immediately
Scripting language  Client side technology  can also be used for exploiting the user’s system.
• Doesn’t have any multiprocessor or multi threading
capabilities.
Interpreter based 
Control Statements 
JavaScript   • As no supports are available, JavaScript cannot be used
Basics 
Case sensitive  for any networking applications.
Looping Statements 
• JavaScript does not allow us to read or write files.
Event handling 
• JavaScript render varies: JavaScript may be rendered
Validating user Input  by different layout engines differently. As a result, this
causes inconsistency in terms of interface and
Built‐in functions 
functionality.

• JavaScript is a object-based scripting language. JavaScript Versions

• It gives the user more control over the browser. JavaScript was invented by Brendan Eich in 1995, and
• It Handles dates and time. became an ECMA standard in 1997. ECMA Script is the
official name of the language.
• It detects the user’s browser and OS,
• It is light weighted. From 2015 ECMA Script is named by year (ECMA
Script 2015).
• It is a scripting language and it is not java.
• It is interpreter based scripting language.
• It is case sensitive.

2 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.94

Copyright Free under CC BY Licence


ECMA Script Editions

Ver Official Name Description

1 ECMA Script 1 (1997) First Edition.

2 ECMA Script 2 (1998) Editorial changes only.

3 ECMA Script 3 (1999) Added Regular Expressions.


Added try/catch.
4 ECMA Script 4 Never released.

5 ECMA Script 5 (2009) Added “strict mode”.


Added JSON support.
Added String.trim().
Added Array.isArray().
Added Array Iteration Methods.
5.1 ECMA Script 5.1 (2011) Editorial changes.

6 ECMA Script 2015 Added let and const.


Added default parameter values.
Added Array.find().Added Array.findIndex().
7 ECMA Script 2016 Added exponential operator (**).
Added Array.prototype.includes.
8 ECMA Script 2017 Added string padding.
Added new Object properties.
Added Async functions.Added Shared Memory.
9 ECMA Script 2018 Added rest/spread properties.
Added Asynchronous iteration.
Added Promise.finally().Additions to Reg Exp.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.94 3

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.95
COPA - JavaScript and creating Web page

Introduction to Web servers and External JavaScript files


Objectives : At the end of this lesson you shall be able to
• explain Web servers and their features
• explain external JavaScript files.

What is Web Server and how it works?


Fig 2

Web servers are core for any web hosting. (Fig 1)

Fig 1
Browser connects to a
Server and requests a Page

Your Local   Server


Computer with Computer with
Web browser web server
software   software
Customization of apache web server is easy as it contains
Server sends back a modular structure. It is also an open source which means
the requested page that can add the own modules to the server when to require
and make modifications that suit the requirements. It is
more stable than any other web servers and is easier to
solve administrative issues. It can be installed on multiple
Web server is a program that uses HTTP to serve files
platforms successfully. Recent apache releases provide
that create web pages to users in response to their
the feasibility of handling more requests when compare to
requests, which is sent by their computers HTTP
its earlier versions.
connection.Any server that delivers an XML document
to another device can be a web server. A better definition
IIS web server
might be that a web server is an Internet server that
responds to HTTP requests to deliver content and
IIS is a Microsoft product. This server has all the features
services.Always a web server is connected to the internet.
just like apache. But it is not an open source and more
Every web server that connects to the Internet will be having
over adding personal modules is not easy and modification
anunique address which contains a series of four
becomes a little difficult job. (Fig 3)
numbers between 0 and 255. A period (.) separates these
numbers.Also, web server enables the hosting providers Fig 3
to manage multiple domains(users) on a single server.A
web host is a company that leases out space on a cluster
of servers to empower people to serve their own content &
webpages.

Different types of web servers

In open market there are different types of web servers


available. Let’s discuss about the most popular web
servers. Apache, IIS, Nginx and Lite Speed are few of
them. Microsoft developed this product and they maintains, thus
it works with all the windows operating system platforms.
Apache web server Also, they provides good customer support if it had any
issues.
One of the most popular web server in the world developed
by the Apache Software Foundation. Apache is an open Nginx web server
source software which supports almost all operating
systems including Linux, Unix, Windows, FreeBSD, Mac Another free open source web server is Nginx, it includes
OS X and more. About 60% of machines run on Apache IMAP/POP3 proxy server. Nginx is known for its high
Web Server. (Fig 2) performance, stability, simple configuration and low
resource usage. (Fig 4)

Copyright Free under CC BY Licence


Fig 4 Now we can import the file in HTML file as follows:-

Importing an external file is relatively painless. First, the


file you are importing must be valid JavaScript, and only
JavaScript. Second, the file must have the file extension
".js". Lastly, you must know the location of the file.

Let us assume we have a file "myjs.js" that contains a


This web server doesn’t use threads to handle requests one line Hello World alert function. Also, let us assume
rather a much more scalable event-driven architecture which that the file is the same directory as the HTML file we are
uses small and predictable amounts of memory under load. going to code up. To import the file you would do the
It is getting popular in the recent times and it is hosting following in your HTML document.
about 7.5% of all domains worldwide. Most of the web
hosting companies are using this in recent times. JavaScript Code:

External JavaScript files: Writing JavaScript within HTML <html>


code sometimes creates confusion, and changing HTML
files may also affect JavaScript files. So better to segregate <head>
HTML and JavaScript files so that, changes in one file <script src="myjs.js">
does not affect other files.
</script>
The external JavaScript files should be written separately </head>
as follows:-
<body>
File myjs.js Contents: <input type="button" onclick="popup()" value="Click Me!">

function popup() { </body>

alert("Hello World"); </html>

} Now this HTML file imports myjs.js file and as a result it


can access popup() function from HTML button element.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.95 5

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.96A
COPA - JavaScript and creating Web page

Using JavaScript Variable and data types


Objectives : At the end of this lesson you shall be able to
• explain variables in JavaScript
• explain various data types in JavaScript.

Variables • Reserved words like JavaScript keywords cannot be


used as names
JavaScript variables are containers for storing data values.
Note: JavaScript identifiers are case-sensitive.
In example 1, a, b, and c, are variables:
The Assignment Operator
Example 1
In JavaScript, the equal sign (=) is an “assignment”
var a = 12; operator, not an “equal to” operator.
var b = 10;
x = x + 10;
var c = a + b;
It assigns the value of x + 10 to x. It calculates the value of
From example 1, we can understand that x + 10 and puts the result into x. The value of x is
incremented by 10.
• a stores the value 12
• b stores the value 10 JavaScript Data Types

• 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.

In programming, just like in algebra, we use variables Example 3


mark1 and mark2 to hold values and use variables in
expressions like total = mark1 + mark2. From the example var pi = 3.14;
above, and calculate the total to be 151. var person = “santhoshkumar”;
var city = “coimbatore”;
JavaScript Identifiers
Declaring JavaScript Variables
All JavaScript variables must be identified with unique
names. These unique names are called identifiers.
Creating a variable in JavaScript is called declaring a
Identifiers can be short names like a and b or more
variable. JavaScript variable is declared with the var
descriptive names like mark1, mark2, total, age, sum,
total volume. keyword.

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”;

Copyright Free under CC BY Licence


In the example below, we create a variable called Example 7
traineeName and assign the value “Santhosh Kumar” to
it. var x = 8 + 2 + 5;

Then we “output” the value inside an HTML paragraph with Now x has the value 15.
id=”demo”:
You can also add strings, but strings will be concatenated:
<p id =“demo”></p>
<script> Example 8

var traineeName = “santhoshkumar”; var x = “Dharani” + “ “ + “Shree”


document.getElementById(“demo”).innerHTML
Now x has the value Dharani Shree
= traineeName;
</script> The result of the following example gives 725.

Note: It is a good programming practice to Example 9


declare all variables at the beginning of a
script. var x = “7” + 2 + 5;

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.

Example 4 The result of the following example gives 75.

var traineeName = “santhoshkumar”,city = Example 10


‘’coimbatore”, total=”151";
var x = 3 + 4 + “5”;
Undefined value
In computer programs, variables are often declared without Data types
a value. The value can be something that has to be
calculated, or something that will be provided later, like In programming, data types is an important concept. To
user input. be able to operate on variables, it is important to know
about the data type.
A variable declared without a value will have the value
undefined. JavaScript variables can hold many data types like
numbers, strings, objects and more.
The variable traineeName will have the value undefined
after the execution of this statement. Example 11

Example 5 var side = 10; // Number


var firstName = “Rithika”; // String
var traineeName;
var x = {firstName:”Harini”, lastName:”Kumar”}; // Object
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable, it will not lose its Without data types, a computer cannot safely solve this.
value.The variable traineeName will still have the value
“santhoshkumar” after the execution of these statements. Example 12

Example 6 var a = 10 + “Apple”;

var traineeName = “santhoshkumar”; JavaScript will treat the example above as,
var traineeName;
var a = “10” + “Apple”;
JavaScript Arithmetic
The output is 10 Apple
Do the arithmetic with JavaScript variables, using operators
like = and + Note: When adding a number and a string,
JavaScript will treat the number as a string.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96A 7

Copyright Free under CC BY Licence


JavaScript evaluates expressions from left to right. Different Example 18
sequences can produce different results.
var num1 = 87.0; // Written with decimals
Example 13
var num2 = 87; // Written without decimals
var y = 20 + 5 + “Apple”;
Extra large or extra small numbers can be written with
The result is 25Apple scientific (exponential) notation:

Example 14 Example 19

var y = “Apple”+20 + 5 ; var exp1 = 232e5; // result is 23200000


The result is Apple205. var z = 123e-5; // result is 0.00232

Note: In the first example, JavaScript treats 20 Example 20


and 5 as numbers, until it reaches “Apple”.In
the second example, since the first operand is var p = 3:
a string, all operands are treated as strings.
var q = 3;
Dynamic data types var r = 5;
(p == q) // Returns true
JavaScript has dynamic types. This means that the same
variable can be used to hold different data types: (p == r) // Returns false

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

The JavaScript typeof operator is used to find the type of


a JavaScript variable.

8 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96A

Copyright Free under CC BY Licence


The typeof operator returns the type of a variable or an Difference Between Undefined and Null
expression.
Undefined and null are equal in value but different in type.
Example 23
Example 28
typeof “” // Returns “string”
typeof undefined // undefined
typeof “Rithika” // Returns “string”
typeof null // object
typeof “Harini Kumar” // Returns “string”
null === undefined // false
typeof0 // Returns “number”
null == undefined // true
typeof81 // Returns “number”
typeof8.14 // Returns “number” Primitive Data
typeof(3+2) // Returns “number”
A primitive data value is a single simple data value with no
additional properties and methods. The typeof operator
Undefined
can return one of these primitive types.
In JavaScript, a variable without a value, has the value • string
undefined. The typeof is also undefined.
• number
Example 24
• boolean
var bike; // Value is undefined, type is
• undefined
undefined
Example 29
Note : Any variable can be emptied, by setting
the value to undefined. The type will also be typeof “Rajesh” // Returns “string”
undefined.
typeof 1.44 // Returns “number”
Empty Values typeof true // Returns “boolean”
An empty value has nothing to do with undefined. An typeof false // Returns “boolean”
empty string has both a legal value and a type. typeof a // if a has no value, it returns
Example 25 “undefined”

var bike = “”; // The value is “”, the typeof Complex Data
is “string”
The typeof operator can return one of two complex types:
Null
• function·
In JavaScript null is “nothing”. It is supposed to be
something that doesn’t exist. In JavaScript, the data type • object
of null is an object. You can empty an object by setting it
to null. The type of operator returns object for both objects, arrays
and null. It does not return object for functions.
Example 26
Example 30
var personName = {firstName:”Harini”,last Name;
”Kumar”, age:13, height:”155 cms”}; typeof {name, ‘Karthik’, age 27} // Returns “object”
personName = null; //Now value in null, but typeof [10, 20, 30, 40, 50] // Returns “object”
type is still an object (not “array”, see
You can also empty an object by setting it to undefined: note below)
typeof null // Returns “object”
Example 27
typeof function sampleFunc() { } // Returns “function”
var personName = {firstName:”Harini”, lastName:
”Kumar”, age:13, height:”155 cms”}; Note: The typeof operator returns “object” for
arrays because in JavaScript arrays are
personName = undefined; // Now both value and objects.
type is undefined.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96A 9

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.96B
COPA - JavaScript and creating Web page

Using JavaScript Constants and Operators


Objectives : At the end of this lesson you shall be able to
• explain constants in JavaScript
• explain operators in JavaScript.

Constants bike.color = “grey”;


// You can add a property:
Constants are a special kind of variable, store a value that
never changes during the course of the program. bike.owner = “Sree”;

The syntax to create a Constant is. But you can NOT reassign a constant object.

const CONSTANT_NAME:DataType = value; Example 4

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

Example 1 You can change the elements of a constant array.

const FRIEND = ‘Shanthi’; Example 5


const BROTHER_AGE = 46;
// You can create a constant array:
Note :The keyword const is a little misleading. constant bikes = [“TVS”, “Yamaha”, “Royal
It does NOT define a constant value. It defines Enfield”];
a constant reference to a value.Because of this,
we cannot change constant primitive values, // You can change an element;
but we can change the properties of constant bikes[0] = “suzuki”;
objects.
bikes.push (“Bajaj”); //you can add an element
Primitive Values But you can NOT reassign a constant array:
If we assign a primitive value to a constant, we cannot Example 6
change the primitive value.
const bikes = {“TVS”, “Yamaha”, “Royal Enfield”];
Example 2
bikes = [“TVS”, “Yamaha”, Bajaj”]; //ERROR
const PI = 3.141592653589793;
Operators
PI = 3.14; // This will give an error
There are eight types of operators in JavaScript. These
PI = PI + 10; // This will also give an are
error
• Additive Operators
Constant Objects can Change
• Multiplicative Operators
Change the properties of a constant object.
• Bitwise operator
Example 3 • Equality operator
// You can create a const object: • Relational Operator
const bike = {type. “Yamaha”, model. “R15”, color. • Unary Operators
“blue”};
• Ternary Operator
// You can change a property:
• Assignment Operators

10

Copyright Free under CC BY Licence


Additive Operators: The term additive operators include Example10
both addition (+) and subtraction( -) as subtraction is also
addition with a negative number. Operation Result Same as Result
Example 7 5&1 1 0101 & 0001 0001

32+67; // this is 99 5|1 5 0101 | 0001 0101

d+e; // Adds d with e ~5 10 ~0101 1010

3-7; // return -4 5 << 1 10 0101 << 1 1010

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

var num1="Runs"; Note: The examples above uses 4 bits unsigned


var num2=784; binary numbers. Because of this ~ 5 returns
10.
var res=num1+num2; // result is Runs784 as java concats
two strings. Since JavaScript uses 32 bits signed integers,
it will not return 10. It will return -6.
Multiplicative Operators: Just like Additive operators,
multiplication(*), division(/) and modulo(%) are multiplicative 00000000000000000000000000000101 (5)
Operators. Modulo operator return remainder of division. 11111111111111111111111111111010 (~5 = -6)
Example 9 A signed integer uses the leftmost bit as the
minus sign.
javascript:alert(4%3); // returns 1
Additive and Multiplicative operator together can be called Equality operator:
Arithmetic Operator.
Equality operator are used to test whether two expressions
Bitwise operator: are the same.
JavaScript Uses 32 bits Bitwise Operands. JavaScript
stores numbers as 64 bits floating point numbers, but all For example "42" and 42 are equal with == but not equal
bitwise operations are performed on 32 bits binary with === as it not only checks for value but also check for
numbers.Before a bitwise operation is performed, type.
JavaScript converts numbers to 32 bits signed integers.
Relational Operator
After the bitwise operation is performed, the result is
converted back to 64 bits JavaScript numbers.
Relational operator checks whether one value is greater
Operator Name Description or less than other value.

& AND Sets each bit to 1 if both Operator Function


bits are 1
| OR Sets each bit to 1 if one of > Greater than
two bits is 1
< Less than
^ XOR Sets each bit to 1 if only
one of two bits is 1 >= Greater than or equal to
~ NOT Inverts all the bits
<= Less than or equal to
<< Zero fill Shifts left by pushing
left shift zeros in from the right and in Tests whether a value is found in
let the leftmost bits fall off an expression
>> Signed Shifts right by pushing
instanceof Tests whether an expression is an
right shift copies of the leftmost bit
instance of an object
in from the left, and let the
rightmost bits fall off
if(5<2) {
>>> Zero fill Shifts right by pushing
right shift zeros in from the left, and // do something
let the rightmost bits fall
off }

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96B 11

Copyright Free under CC BY Licence


The less than operator checks whether the first value is and q=a++; is equivalent to
less than second value and if valid, it returns false. In the
above example, 5 is not less than 2, so it is not true and q=a;
code inside the if block will not execute. a=a+1;
The other three operator are in the same way do checking
The delete Operator
for greater then (>),Greater than or equal to(>=), Less than
or equal to (<=). The delete operator can be used to delete properties from
objects.
in operator checks whether a given index is contained
within an object. For example: Example 13
var MyObj= {star:"Algol", constellation: "Perseus"}; var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
if("star" in MyObj) {
delete person.age;
// do something
The delete operator is designed to be used on object
}
properties. It has no effect on variables or functions.
As star is a index the code will work. but in operator do The delete operator should not be used on predefined Java
not work on numeric types as it works for numbers only. Script object properties. It can crash your application.
Instanceof Operator checks whether an object instance
The Unary + Operator
or object variable of is an instance of a particular object.
The unary + operator can be used to convert a variable to
Example 11
a number.
var mydate=new Date(); Example 14
if(mydate instanceof Date) {
var y = "5"; // y is a string
//do something var x = + y; // x is a number
}
If the variable cannot be converted, it will still become a
number, but with the value NaN (Not a number):
Here mydate is an instance of built-in Date object. So the
code will be executed within the if block. Example 15
Unary Operator
var y = "John"; // y is a string
delete, void, typeof, ++, --, + , -, ~ , ! are unary operators
var x = + y; // x is a number (NaN)
in Javascript.
In the same way Unary - Operator also operates.
Example 12
Ternary or Conditional Operator: It can be used as
a = -10;
compact if else.
p=++a; Example 16
q=a++;
a = (b>5 ? 4:7); means
s=+p;
if(b>5)
There are pre and post increment and decrement operator.
a=4;
p=++a; is equivalent to
else
a=a+1; a=7;
p=a;

12 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96B

Copyright Free under CC BY Licence


Assignment Operator: a = q; means value of q is assigned into a variable deleting
the previous value of a.
Assignment Operator is used to assign values into a
variable. Apart from = there are compound assignment Now a* = 3; is equivalent to a = a*3; and like that all other
operators as follows- compound assignment operator behaves.

*= /= %=

+= -= <<=

>>= >>>= &=

^= |=

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96B 13

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.97A & 2.1.97B
COPA - JavaScript and creating Web page

Control statements, Loops and Popup boxes in JavaScript


Objectives : At the end of this lesson you shall be able to
• explain control statements
• discuss about various Loops
• explain the uses of Popup boxes.

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

The if Statement The else if Statement

Use the if statement to specify a block of JavaScript code Use the else if statement to specify a new condition if the
to be executed if a condition is true. first condition is false.
Syntax Syntax
If (condition) { if (condition1) {
block of code to be executed if the condition is true block of code to be executed if condition1 is true
} } else if (condition2) {
block of code to be executed if the condition1 is false
Example 1
and condition2 is true
Make a "Good day" greeting if the time is less than 18:00: } else {
if (time < 18) { block of code to be executed if the condition1 is false
and condition2 is false
greeting = "Good day";
}
}
The result of greeting will be: Example 3
Good day
If time is less than 10:00, create a "Good morning"
greeting, if not, but time is less than 18:00, create a "Good
The else Statement
day" greeting, otherwise a "Good evening":
Use the else statement to specify a block of code to be
if (time < 10) {
executed if the condition is false.
greeting = "Good morning";
if (condition) {
} else if (time < 18) {
block of code to be executed if the condition is true
greeting = "Good day";
} else {
} else {

14

Copyright Free under CC BY Licence


greeting = "Good evening"; case 4:
} day = "Thursday";
The result of x will be: break;
Good day case 5:
day = "Friday";
The JavaScript Switch Statement
break;
Use the switch statement to select one of many blocks of
case 6:
code to be executed.
day = "Saturday";
Syntax
break;
switch(expression) {
}
case n1:
The result of day will be:
code block
Tuesday
break;
case n2: The break Keyword
code block
When the JavaScript code interpreter reaches a break
break; keyword, it breaks out of the switch block.
default: This will stop the execution of more execution of code
and/or case testing inside the block.
default code block
} The default Keyword

This is how it works: The default keyword specifies the code to run if there is no
case match:
• The switch expression is evaluated once.
Example 5
• The value of the expression is compared with the values
of each case.
If today is neither Saturday nor Sunday, write a default
• If there is a match, the associated block of code is message:
executed.
switch (new Date().getDay()) {
Example 4
case 6:
Use today's weekday number to calculate weekday name: text = "Today is Saturday";
(Sunday=0, Monday=1, Tuesday=2, ...)
break;
switch (new Date().getDay()) {
case 0:
case 0:
text = "Today is Sunday";
day = "Sunday";
break;
break;
default:
case 1:
text = "Looking forward to the Weekend";
day = "Monday";
}
break;
The result of text will be:
case 2:
Looking forward to the Weekend
day = "Tuesday";
Common Code and Fall-Through
break;
case 3: Sometimes, in a switch block, you will want different cases
to use the same code, or fall-through to a common default.
day = "Wednesday";
Note from the next example, that cases can share the
break;
same code block and that the default case does not have
to be the last case in a switch block:

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.97A & 2.1.97B 15

Copyright Free under CC BY Licence


Example 6 The For Loop

switch (new Date().getDay()) { The for loop is often the tool you will use when you want to
create a loop.
case 1:
case 2: The for loop has the following syntax:
case 3:
for (statement 1; statement 2; statement 3) {
default:
code block to be executed
text = "Weekend is coming";
break; }
case 4:
Statement 1 is executed before the loop (the code block)
case 5: starts. It is called Initialisation Part
text = "Weekend is soon";
Statement 2 defines the condition for running the loop (the
break; code block).It is called condition part.
case 0:
Statement 3 is executed each time after the loop (the
case 6: code block) has been executed. It is called increment/
decrement part.
text = "Now in Weekend";
} Example 7

JavaScript Loops for (i = 0; i < 5; i++) {

Loops are handy, if you want to run the same code over text += "The number is " + i + "<br>";
and over again, each time with a different value.
}
Often this is the case when working with arrays:
Instead of writing: From the example above, you can read:
text += train[0] + "<br>"; Statement 1 sets a variable before the loop starts
text += train [1] + "<br>"; (var i = 0).
text += train [2] + "<br>"; Statement 2 defines the condition for the loop to run
text += train [3] + "<br>"; (i must be less than 5).
text += train [4] + "<br>"; Statement 3 increases a value (i++) each time the code
text += train [5] + "<br>"; block in the loop has been executed.
You can write:
Initialisation Part
for (i = 0; i < train.length; i++) {
Normally you will use statement 1 to initiate the variable
text += train [i] + "<br>";
used in the loop (var i = 0).
} This is not always the case, JavaScript doesn't care.
Statement 1 is optional.
Different Kinds of Loops
You can initiate many values in statement 1 (separated
JavaScript supports different kinds of loops:
by comma):
• for - loops through a block of code a number of times
Example 8
• for/in - loops through the properties of an object
for (i = 0, len = train.length, text = ""; i < len; i++) {
• while - loops through a block of code while a specified
condition is true
text += train [i] + "<br>";
• do/while - also loops through a block of code while a
specified condition is true }

And you can omit statement 1 (like when your values are
set before the loop starts):

16 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.97A & 2.1.97B

Copyright Free under CC BY Licence


Example 9 text += person[x];
}
var i = 2;
var len = train.length; While Loop
var text = "";
The while loop loops through a block of code as long as a
for (; i < len; i++) { specified condition is true.
text += train [i] + "<br>"; Syntax
} while (condition) {
code block to be executed
Condition Part
}
Often statement 2 is used to evaluate the condition of the
initial variable. In the following example, the code in the loop will run, over
and over again, as long as a variable (i) is less than 10:
This is not always the case, JavaScript doesn't care.
Statement 2 is also optional. Example 11

If statement 2 returns true, the loop will start over again, if while (i < 10) {
it returns false, the loop will end.
text += "The number is " + i;
If you omit statement 2, you must provide a break inside i++;
the loop. Otherwise the loop will never end. This will crash
}
your browser. Read about breaks in a later chapter of this
tutorial. If you forget to increase the variable used in the condition,
the loop will never end. This will crash your browser.
Increment/Decrement Part
The Do/While Loop
Often statement 3 increases the initial variable.
The do/while loop is a variant of the while loop. This loop
This is not always the case, JavaScript doesn't care, and
will execute the code block once, before checking if the
statement 3 is optional.
condition is true, then it will repeat the loop as long as the
condition is true.
Statement 3 can do anything like negative increment (i--),
or larger increment (i = i + 15), or anything else. Syntax

Statement 3 can also be omitted (like when you increment do {


your values inside the loop):
code block to be executed
Example 10 }
while (condition);
var i = 0;
len = train.length; The example below uses a do/while loop. The loop will
always be executed at least once, even if the condition is
for (; i < len; ) {
false, because the code block is executed before the
text += train [i] + "<br>"; condition is tested:
i++;
Example 12
}
do {
For/In Loop
text += "The number is " + i;
The JavaScript for/in statement loops through the properties i++;
of an object:
}
var person = {fname:"Raja", lname:"Sen", age:35}; while (i < 10);
var text = ""; Do not forget to increase the variable used in the condition,
otherwise the loop will never end!
var x;
for (x in person) {
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.97A & 2.1.97B 17

Copyright Free under CC BY Licence


Comparing For and While Popup Boxes
JavaScript has three kind of popup boxes. They are
If you have read the previous chapter, about the for loop,
you will discover that a while loop is much the same as a
1 Alert box
for loop, with statement 1 and statement 3 omitted.
2 Confirm box and
The loop in this example uses a for loop to collect the car
names from the train array: 3 Prompt box.

Example 13 Alert Box

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++;
}

The Break Statement in Loop Confirm Box

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”);

for(i=0;i<l;i++ { Note: The window.confirm() method can be


written without the window prefix.
if(arr[i]==item) {
alert("Found at :"+i); Example 16

fl=1; if (confirm(“Click a button!”))


break; {
} txt = “ You clicked OK!”;
if(fl==0) alert("Not Found"); }

Here, if the item is found, loop breaks and CPU time is else
saved. {
txt = “You clicked Cancel!”;

}
18 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.97A & 2.1.97B

Copyright Free under CC BY Licence


The result is is shown in Fig 2. The result is is shown in Fig 3.
Fig 2 Fig 3

Note: When click on OK button it displays the


message “You clicked OK!” and when click on Note: If click on OK button it displays the
Cancel button it displays the message “You message “Hello Lakshmi! Congratulations!!!!!”
clicked Cancel!” If cancelled the name ‘Lakshmi’ as shown in
Fig 4 it gives the message “User cancelled the
Prompt Box Prompt”. Also whenclick the Cancel button
even when if the box has text ‘Lakshmi’ it gives
A prompt box is often used if the user to input a value the message “User cancelled the Prompt”.
before entering a page.When a prompt box pops up, the
user will have to click either “OK” or “Cancel” to proceed Fig 4
after entering an input value.If the user clicks “OK” the box
returns the input value. If the user clicks “Cancel” the box
returns null.

Syntax

window.prompt(“sometext”,”default text”);

Note: The window.prompt() method can be


written without the window prefix.
Line Breaks
Example 17
To display line breaks inside a popup box, use a back-
var tname = promp t(“Please Enter your Name”, “Lakshmi”); slash followed by the character n.
if (tname == null || tname == “”) Example 18
{txt = “User cancelled the prompt.”;
} alert(“Hello\nWelcome!”);
else The result is shown in Fig 5.
{txt = “Hello “ + tname + “! Congratulations!!!!!”); Fig 5
}

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.97A & 2.1.97B 19

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.98A & 2.1.98B
COPA - JavaScript and creating Web page

Error handling in JavaScript


Objectives : At the end of this lesson you shall be able to
• know types of errors in JavaScript
• explain error handling in JavaScript.

Types of Errors You cannot catch those errors, because it depends on


your requirement what type of logic you want to put in
There are three types of errors in programming: your program.

a Syntax Errors JavaScript Errors - Throw and Try to Catch


b Runtime Errors
The try statement is used to test a block of code for errors.
c Logical Errors. The catch statement is used to handle the error. The throw
statement is used to create custom errors. The finally
Syntax Errors statement is used to execute code, after try and catch,
regardless of the result.
Syntax errors, also called parsing errors, occur at
compile time in traditional programming languages and at When executing JavaScript code, different errors can occur.
interpret time in JavaScript. Errors can be coding errors made by the programmer,
errors due to wrong input, and other unforeseeable things.
For example, the following line causes a syntax error
because it is missing a closing parenthesis. Example 1

<script type=”text/javascript”> In this example we have written alert as addalerte to


window.print(“Good Morning”); deliberately produce an error.

</script> <p id = “sample”></p>

Note : When a syntax error occurs in JavaScript, <script>


only the code contained within the same thread try {
as the syntax error is affected and the rest of
addalerte (“Success!”);
the code in other threads gets executed
assuming nothing in them depends on the code }
containing the error.
catch (err) {
Runtime Errors document.getElement ById(“sample”).innerHTML =
err.message;
Runtime errors, also called exceptions, occur during
}
execution (after compilation/interpretation).
</script>
For example, the following line causes a runtime error
because here the syntax is correct, but at runtime, it is JavaScript catches addalerte as an error and executes
trying to call a method that does not exist. the catch code to handle it.

<script type=”text/javascript”> JavaScript try and catch


window.printme();
The try statement is used to define a block of code to be
</script> tested for errors while it is being executed. The catch
statement is used to define a block of code to be executed,
Logical Errors if an error occurs in the try block.

Logic errors can be the most difficult type of errors to The JavaScript statements try and catch come in pairs.
track down. These errors are not the result of a syntax or
try {
runtime error. Instead, they occur when you make a mistake
in the logic that drives your script and you do not get the Block of code to try
result you expected.
}

20

Copyright Free under CC BY Licence


catch (err){ }
Block of code to handle errors catch (err) {
} message.innerHTML = “Input is” + err;
JavaScript Throws Errors }
}
When an error occurs, JavaScript will normally stop and
generate an error message. This is technically called throw </script>
an exception (throw an error). JavaScript will actually
</body>
create an Error object with two properties - name and
message. </html>

The throw Statement Statement

The throw statement allows you to create a custom error. The finally statement lets you execute code, after try
The exception can be a JavaScript String, a Number, a and catch, regardless of the result:
Boolean or an Object:
try {
throw “very small”; // throw a text Block of code to try
throw 1000; // throw a number }
catch (err) {
Note: If you use throw together with try and
catch, you can control program flow and Block of code to handle errors
generate custom error messages. }
Input Validation Example finally {
This example examines input. If the value is wrong, an Block of code to be executed regardless of the try/
exception is thrown. The exception (err) is caught by the catch result
catch statement and a custom error message is displayed: }
<IDOCTYPE html> Example 2
<html>
function myFunction() {
<body>
var message, x;
<p>please input a number between 40 and 100</p>
message = document.getElementById(“s1”);
<input id = “demo” type = “text”>
message.innerHTML = “”;
<button type = “button”onclick = “myFunction()” >
x = document.getElementById(“demo”).value;
Sample Input </button>
try {
<p id = “s1”></p>
if (x ==””) throw “is empty”;
<script>
if (isNaN(x)) throw “is not a number”;
function myFunction() {
x = Number(x);
var message, x;
if (x>10) throw “is too high”;
message = document.get Element By Id (“s1”)
if (x<5) throw “is too low”;
message.inner HTML = “”,
}
x = document.getElementById(“demo”).value;
catch (err) {
try {
message.innerHTML = “Error:” + err + “.”;
if (x ==””) throw “nil”;
}
if (isNaN(x)) throw “not a number”;
finally {
x = Number(x);
document.getElementById (“demo”).value = “”;
if (x < 40) throw “too low”;
}
if (x > 100) throw “too high”;
}
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.98A & 2.1.98B 21

Copyright Free under CC BY Licence


The Error Object }
JavaScript has a built in error object that provides error catch (err) {
information when an error occurs. The error object provides
document.getElementById(“demo”).innerHTML =
two useful properties - name and message.
err.name;
Property Description
}
Name - Sets or returns an error name
Syntax Error
message - Sets or returns an error message (a
string)
A SyntaxError is thrown if you try to evaluate code with a
syntax error.
Error Name Values
Example 5
Six different values can be returned by the error name
property. They are
try {
Error Name Description
Eval Error - An error has occurred in the eval() eval (“alert (“Welcome’); // Missing “will produce
function an error
Range Error - A number “out of range” has occurred }
Reference catch (err) {
Error - An illegal reference has occurred document.getElementById(“demo”).innerHTML
Syntax = err.name;
Error - A syntax error has occurred }
Type Error - A type error has occurred
Type Error
URI Error - An error in encodeURI() has occurred
A TypeError is thrown if you use a value that is outside
Eval Error the range of expected types.
An Eval Error indicates an error in the eval() function.
Example 6
Range Error
var num = 10;
A RangeError is thrown if you use a number that is
try {
outside the range of legal values.
num.toUpperCase(); // You cannot convert a
Example 3 number to upper case
}
var num = 1;
catch (err) {
try {
document.getElementById(“demo”).innerHTML =
num.to Precision (200); // A number cannot have 200 err.name;
significant digits
}
}
catch (err) { URI (Uniform Resource Identifier) Error

document.get Element By Id (“demo”).inner HTML = A URIError is thrown if you use illegal characters in a URI
err.name; function:

} Example
try {
Reference Error
decode URI (“%%”); // You cannot use URI
A ReferenceError is thrown if you use a variable that has decode percent signs
not been declared.
}
Example 4
catch (err) {
var x;
document.getElementById(“demo”).innerHTML =
try { err.name
x = y + 1; // cannot be referenced. }

22 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.98A & 2.1.98B

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.99
COPA - JavaScript and creating Web page

Arrays in JavaScript
Objectives : At the end of this lesson you shall be able to
• define Array
• explain concepts of Array
• describe array methods
• know sorting of Array.

What is an Array? Access the Elements of an 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 = "Jan Satabdi"; var name = trains[0];

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":

JavaScript arrays are used to store multiple values in a Example 3


single variable.
<p id="demo"></p>
Creating an Array
<script>
Using an array literal is the easiest way to create a var trains = ["Duronto", "Jan Satabdi", "RAJDHANI"];
JavaScript Array.
document.getElementById("demo").innerHTML = trains;
Syntax: </script>

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.

The following example also creates an Array and assigns Example 4


values to it:
var trains = [
Example 2
"Duronto",
var trains = new Array("Duronto", "Jan Satabdi", "Jan Satabdi",
"RAJDHANI");
"RAJDHANI"
The two examples above do exactly the same. There is
no need to use new Array(). ];
For simplicity, readability and execution speed, use the
first one (the array literal method).

23

Copyright Free under CC BY Licence


Don't put a comma after the last element (like Example 7
"RAJDHANI",). It is inconsistent across browsers.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
An array can hold many values under a single name and
fruits[fruits.length] = "Lemon"; // adds a new element
you can access the values by referring to an index number.
(Lemon) to fruits
You can have different objects in one array
Adding elements with high indexes can create undefined
"holes" in an array:
JavaScript variables can be objects. Arrays are special
kinds of objects.
Example 8
Because of this, you can have variables of different types
var fruits = ["Banana", "Orange", "Apple", "Mango"];
in the same Array.
fruits[10] = "Lemon"; // adds a new element (Lemon) to
You can have objects in an Array. You can have functions fruits
in an Array. You can have arrays in an Array:
Looping Array Elements
my Array[0] = Date.now;
The best way to loop through an array is using a standard
my Array [1] = my Function;
for loop:
my Array [2] = myTrains;
Example 9
Arrays are Objects
var index;
Arrays are a special type of objects. The typeof operator
var fruits = ["Banana", "Orange", "Apple", "Mango"];
in JavaScript returns "object" for arrays.
for (index = 0; index < fruits.length; index++) {
But, JavaScript arrays are best described as arrays.
text += fruits[index];
Arrays use numbers to access its "elements". In this }
example, person[0] returns Raja:
Associative Arrays? No Way!
Array
Many programming languages support arrays with named
var person = ["Raja", "Sen", 46]; indexes.
Arrays with named indexes are called associative arrays
Objects use names to access its "members". In this
(or hashes).
example, person.firstName returns Raja:
JavaScript does not support arrays with named indexes.
Object
Wrong:
var person = {firstName:"Raja", lastName:"Sen", age:46};
var person = new Array()
The length Property
person ["firstName"] = "Raja";
The length property of an array returns the length of an person ["lastName"] = "Sen";
array (the number of array elements).
person ["age"] = 46;
Example 6
The example above looks like it works. But it does not.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
If you try it, person ["firstName"] will return Raja, but person
[0] will return undefined, and person.length will return 0.
fruits.length; // the length of fruits is 4
If you want to create an associative array, create an object
The length property is always one more than the highest
instead.
array index.
When to Use Arrays? When to use Objects?
Adding Array Elements
JavaScript does not support associative arrays.
The easiest way to add a new element to an array is to
use the length property:
You should use objects when you want the element names
to be strings.

24 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.99

Copyright Free under CC BY Licence


You should use arrays when you want the element names JavaScript Array Methods
to be sequential numbers.
Converting Arrays to Strings
Avoid new Array()
toString() method
There is no need to use the JavaScript's built-in array
constructor new Array(). The JavaScript method toString() converts an array to a
string of (comma separated) array values.
Use [] instead.
Example 10
These two different statements both create a new empty
array named points. var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”,”Fitter”];
document.getElementById(“demo”).innerHTML =
var points = new Array(); // Bad
trade.toString();
var points = []; // Good
Result
These two different statements both create a new array
containing 6 numbers. COPA,IT,ICTSM,CHNM,Fitter

var points = new Array(40, 100, 1, 5, 25, 10) // Bad join() method
var points = [40, 100, 1, 5, 25, 10]; // Good
The join() method also joins all array elements into a
string.It behaves just like toString(), but in addition you
The new keyword complicates your code and produces
can specify the separator.
nasty side effects.
Example 11
var points = new Array(40, 100); // Creates an array with
two elements (40 and 100) var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”,”Fitter”];
document.getElementById(“demo”).innerHTML =
What if I remove one of the elements?
trade.join(“-”);
var points = new Array(40); // Creates an array with 40
undefined elements !!!!! Result
COPA - IT – ICTSM – CHNM - Fitter
How to Recognize an Array?
Popping and Pushing
A common question is: How do I know if a variable is an
array? When you work with arrays, it is easy to remove elements
and add new elements.
The problem is that the JavaScript operator type of returns
"object": Popping

var fruits = ["Banana", "Orange", "Apple", "Mango"]; The pop() method removes the last element from an array.
typeof fruits; // typeof returns object
Example 12
The type of operator returns object because a JavaScript
var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”,”Fitter”];
array is an object.
trade.pop(); // Removes the last element (“Fitter”) from
To solve this problem you can create your own isArray() trade.
function:
Result
function isArray(myArray) {
COPA,IT,ICTSM,CHNM
return myArray.constructor.toString().indexOf("Array") > 1;
} The pop() method returns the value that was “popped out”.

The function above always return true if the argument is Example 13


an array.
var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”];
Or more precisely: it returns true if the object proto type of var x = trade.pop(); // the value of x is
the argument is "[object array]". “CHNM”.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.99 25

Copyright Free under CC BY Licence


Pushing Example 19

The push() method adds a new element to an array (at var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”];
the end). trade.unshift(“ElecMech”); // Returns 5
Example 14 Changing Elements
var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”];
Array elements are accessed using their index
trade.push(“DTPO”); // Adds a new element (“DTPO”) number:Array indexes start with 0. [0] is the first array
to trade. element, [1] is the second, [2] is the third ...

Result Example 20

COPA,IT,ICTSM,CHNM,DTPO var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”];


trade[2] = “DTPO”; // Changes the third element of
The push() method returns the new array length.
trade to “DTPO”
Example 15
Result
var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”]; COPA,IT,DTPO,CHNM
var x = trade.push(“DTPO”); // the value of x is 5
The length property provides an easy way to append a
Shifting Elements new element to an array:

Shifting is equivalent to popping, working on the first Example 21


element instead of the last. The shift() method removes
the first array element and “shifts” all other elements to a var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];
lower index. trade[trade.length] = “ICTSM”; // Appends “ICTSM”
to fruits
Example 16
Result
var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”];
trade.shift(); // Removes the first element “COPA” from COPA,IT,DTPO,CHNM,ICTSM
trade.
Deleting Elements
Result
Since JavaScript arrays are objects, elements can be
IT,ICTSM,CHNM deleted by using the JavaScript operator delete.

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

Result var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];

ElecMech,COPA,IT,ICTSM,CHNM trade.splice(2, 0, “Turner”, “Machinist”);

The unshift() method returns the new array length.

26 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.99

Copyright Free under CC BY Licence


Note: The first parameter (2) defines the var arr3 = [“Ramya”,”Kavi”];
position where new elements should be added var myTrainee = arr1.concat(arr2, arr3);
(spliced in).The second parameter (0) defines // Concatenates arr1 with arr2 and arr3
how many elements should be removed.The
rest of the parameters (“Turner”, The concat() method can also take values as arguments.
“Machinist”)define the new elements to be
added. Example 27 (Merging an Array with Values)

Result var arr1 = [“Priya”, “Mythili”];

COPA,IT,Turner,Machinist,DTPO,CHNM var myTrainee = arr1.concat([“Ramya”,”Kavi”]);

Using splice() to Remove Elements Slicing an Array

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”];

Result var trade1 = trade.slice(2);

IT,DTPO,CHNM The slice() method can take two arguments like slice
(1, 3). The method then selects elements from the start
Note :The first parameter (0) defines the argument, and up to (but not including) the end argument.
position where new elements should be added
(spliced in). The second parameter (1) defines Example 29
how many elements should be removed.The
rest of the parameters are omitted. No new var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];
elements will be added. var trade1 = trade.slice(1,3);

Merging or Concatenating Arrays If the end argument is omitted, like in the first examples,
the slice() method slices out the rest of the array.
The concat() method creates a new array by merging
existing arrays. Example 30

Example 25 (Merging Two Arrays) var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];
var trade1 = trade.slice(2);
var names1 = [“Devi”, “Deepa”];
var names2 = [“Poorna”, “Saranya”, “Shalini”]; Automatic toString()
var myTrainee = names1.concat(names2); JavaScript automatically converts an array to a comma
//Concatenates (joins) names1 and names2. separated string when a primitive value is expected. This
is always the case when you try to output an array.
Result
These two examples will produce the same result:
Note: The concat() method does not change
the existing arrays. It always returns a new
Example 31
array.
var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];
The concat() method can take any number of array
arguments. document.getElementById(“demo”).innerHTML =
trade.toString();
Example 26 (Merging Three Arrays)
Example 32
var arr1 = [“Priya”, “Mythili”];
var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];
var arr2 = [“Sangeetha”, “Nancy”, “Sahana”];
document.getElementById(“demo”).innerHTML = trade;

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.99 27

Copyright Free under CC BY Licence


Note: All JavaScript objects have a toString() Reversing an Array
method.
The reverse() method reverses the elements in an
Sorting an Array array.You can use it to sort an array in descending order.

The sort() method sorts an array alphabetically. Example 34


Example 33 var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”];
trade.sort(); // Sorts the elements of trade
var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”];
trade.sort(); // Sorts the elements of trade trade.reverse(); // Reverse the order of the elements
Result

CHNM,COPA,ICTSM,IT

28 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.99

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.100A
COPA - JavaScript and creating Web page

Introduction to Function in JavaScript


Objectives : At the end of this lesson you shall be able to
• define function
• explain working of function
• explain the benifit of using function
• explain scope of variables.

JavaScript Functions: A JavaScript function is a block Function Return


of code designed to perform a particular task.
When JavaScript reaches a return statement, the function
A JavaScript function is executed when "something" will stop executing. If the function was invoked from a
invokes it (calls it). statement, JavaScript will "return" to execute the code
after the invoking statement. Functions often compute a
Example 1 return value. The return value is "returned" back to the
"caller":
function myFunction(p1, p2) {
Example 2
return p1 * p2; // the function returns the product of p1
and p2
Calculate the product of two numbers, and return the result:
}
var x = myFunction(4, 3); // Function is called, return
JavaScript Function Syntax value will end up in x
function myFunction(a, b) {
A JavaScript function is defined with the function keyword,
followed by a name, followed by parentheses (). return a * b; // Function returns the product of a and b }
The result in x will be: 12
Function names can contain letters, digits, underscores,
and dollar signs (same rules as variables).
Why Functions?
The parentheses may include parameter names separated
You can reuse code: Define the code once and use it
by commas: (parameter1, parameter2, ...)
many times. You can use the same code many times
with different arguments, to produce different results.
The code to be executed, by the function, is placed inside
curly brackets: {}
Example 3
functionName(parameter1, parameter2, parameter3) {
Convert Fahrenheit to Celsius:
code to be executed function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
}
Function parameters are the names listed in the function
definition. Function arguments are the real values received JavaScript Functions are Objects
by the function when it is invoked. Inside the function, the
arguments are used as local variables. A Function is much In JavaScript, functions are objects. JavaScript functions
the same as a Procedure or a Subroutine, in other have properties and methods. You can add your own
programming languages. properties and methods to functions.

Function Invocation JavaScript Functions are Variables Too

The code inside the function will execute when "something" In JavaScript, functions can be used as variables:
invokes (calls) the function.
Example 4
• When an event occurs (when a user clicks a button)
Instead of:
• When it is invoked (called) from JavaScript code
• Automatically (self invoked) temp = toCelsius(32);

29

Copyright Free under CC BY Licence


text = "The temperature is " + temp + " Centigrade"; Automatically Global

You can use: If you assign a value to a variable that has not been de-
clared, it will automatically become a GLOBAL variable.
text = "The temperature is " + toCelsius(32) + " Centigrade";
This code example will declare train as a global variable,
JavaScript functions can be redefined like ordinary even if it is executed inside a function.
variables. It can also be passed as values to other
functions. Example 7

JavaScript Scope // code here can use train


function myFunction() {
Scope is the set of variables you have access to.
train = "Jan Satabdi";
In JavaScript, objects and functions, are also variables. In
// code here can use train
JavaScript, scope is the set of variables, objects, and func-
tions you have access to. JavaScript has function scope: }
The scope changes inside functions.
The Lifetime of JavaScript Variables
Local JavaScript Variables
The lifetime of a JavaScript variable starts when it is de-
Variables declared within a JavaScript function, become
clared. Local variables are deleted when the function is
LOCAL to the function. Local variables have local scope.
completed. Global variables are deleted when you close
They can only be accessed within the function.
the page.
Example 5
Function Arguments
// code here can not use train
Function arguments (parameters) work as local variables
function myFunction() { inside functions.
var train = "Jan Satabdi";
Global Variables in HTML
// code here can use train
With JavaScript, the global scope is the complete
}
JavaScript environment.
Since local variables are only recognized inside their func-
In HTML, the global scope is the window object: All global
tions, variables with the same name can be used in differ-
variables belong to the window object.
ent functions. Local variables are created when a function
starts, and deleted when the function is completed.
Example 8
Global JavaScript Variables
// code here can use window.train
A variable declared outside a function, becomes GLOBAL.
function myFunction() {
A global variable has global scope: All scripts and func-
tions on a web page can access it. train = "Jan Satabdi";
}
Example 6
var train = " Jan Satabdi";
// code here can use train
function myFunction() {
// code here can use train
}

30 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.100A

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.100B
COPA - JavaScript and creating Web page

Objects in JavaScript
Objectives: At the end of this lesson you shall be able to
• define object
• explain object and OOP concept
• explain terminology related to objects.

Introduction to Object-Oriented JavaScript Property

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

Object-oriented programming is intended to promote The conjunction of complex inheritance, methods,


greater flexibility and maintainability in programming and properties of an object must be able to simulate a reality
is widely popular in large-scale software engineering. By model.
virtue of its strong emphasis on modularity, object oriented
code is intended to be simpler to develop and easier to Polymorphism
understand later on, lending itself to more direct analysis,
Poly means "many" and morphism means "forms".
coding, and understanding of complex situations and
Different classes might define the same method or property.
procedures than less modular programming methods1.
For a more extensive description of object-oriented
Terminology
programming, see Object-oriented programming at
Namespace Wikipedia.

A container which allows developers to bundle all Prototype-based programming


functionality under a unique, application-specific name.
Prototype-based programming is a style of object-oriented
Class programming in which classes are not present, and
behavior reuse (known as inheritance in class-based
Defines the characteristics of the object. It is a template languages) is accomplished through a process of
definition of variables and methods of an object. decorating existing objects which serve as prototypes.

Object This model is also known as class-less, prototype-oriented,


or instance-based programming.
An Instance of a class.

31

Copyright Free under CC BY Licence


The original (and most canonical) example of a prototype- },
based language is the programming language Self
validatePhoneNo: function(phoneNo){
developed by David Ungar and Randall Smith. However,
the class-less programming style has recently grown // do something with phone number
increasingly popular, and has been adopted for }
programming languages such as JavaScript, Cecil,
NewtonScript, Io, MOO, REBOL, Kevo, Squeak (when }
using the Viewer framework to manipulate Morphic // Object together with the method declarations
components), and several others.
MYAPP.event = {
JavaScript Object Oriented Programming addListener: function(el, type, fn) {
Namespace // code stuff
},
A namespace is a container which allows developers to
bundle up all functionality under a unique, application- removeListener: function(el, type, fn) {
specific name. In JavaScript a namespace is just another // code stuff
object containing methods, properties and objects.
},
It is very important to note that there is no language-level getEvent: function(e) {
difference between regular object and namespaces as there
is in some other object-oriented languages. // code stuff
}
The idea behind creating a namespace in JavaScript is
simple: one global object is created and all variables, // Can add another method and properties
methods and functions become properties of that object. }
Use of namespaces also minimizes the possibility of name
conflicts in an application. //Syntax for Using addListner method:

Let's create a global object called MYAPP MYAPP.event.addListener("yourel", "type", callback);

// global namespace Core Objects

var MYAPP = MYAPP || {}; JavaScript has several objects included in its core, for
example, there are objects like Math, Object, Array and
Here in above code sample we have first checked whether String. The example below shows how to use the Math
MYAPP is already defined (either in same file or in another object to get a random number by using its random()
file). If yes, then use the existing MYAPP global object, method.
otherwise create an empty object called MYAPP which
will encapsulate method, functions, variables and objects. alert(Math.random());

We can also create sub-namespaces: This and all further examples presume a
function named alert (such as the one included
// sub namespace in web browsers) is defined globally. The alert
function is not actually a part of JavaScript
MYAPP.event = {}; itself.
Below is code syntax for creating namespace and adding See JavaScript Reference: Global Objects for a list of the
variable, function and method: core objects in JavaScript.
// Create container called MYAPP.commonMethod for Every object in JavaScript is an instance of the object
common method and properties Object and therefore inherits all its properties and methods.
Custom Objects
MYAPP.commonMethod = {
The Class
regExForName: "", // define regex for name validation
regExForPhone: "", // define regex for phone no validation JavaScript is a prototype-based language which contains
no class statement, such as is found in C++ or Java. This
validateName: function(name){ is sometimes confusing for programmers accustomed to
// Do something with name, you can access languages with a class statement. Instead, JavaScript uses
regExForName variable functions as classes. Defining a class is as easy as
defining a function. In the example below we define a new
// using "this.regExForName"
class called Person.

32 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.100B

Copyright Free under CC BY Licence


function Person() { } In the example below we define the firstName property for
the Person class and we define it at instantiation.
or
function Person(firstName) {
var Person = function(){ }
this.firstName = firstName;
The Object (Class Instance)
alert('Person instantiated');
To create a new instance of an object obj we use the
}
statement new obj, assigning the result (which is of type
obj) to a variable to access it later. var person1 = new Person('Alice');
var person2 = new Person('Bob');
In the example below we define a class named Person
and we create two instances (person1 and person2). // Show the firstName properties of the objects
alert('person1 is ' + person1.firstName); // alerts "person1
function Person() { }
is Alice"
var person1 = new Person();
alert('person2 is ' + person2.firstName); // alerts "person2
var person2 = new Person(); is Bob"

Please also see Object.create for a new and alternative The Methods
instantiation method.
Methods follow the same logic as properties; the difference
is that they are functions and they are defined as functions.
The Constructor
Calling a method is similar to accessing a property, but
The constructor is called at the moment of instantiation you add () at the end of the method name, possibly with
(the moment when the object instance is created). The arguments. To define a method, assign a function to a
constructor is a method of the class. In JavaScript, the named property of the class's prototype property; the name
function serves as the constructor of the object therefore, that the function is assigned to is the name that the method
there is no need to explicitly define a constructor method. is called by on the object.
Every action declared in the class gets executed at the
In the example below we define and use the method
time of instantiation.
sayHello() for the Person class.
The constructor is used to set the object's properties or to
function Person(firstName) {
call methods to prepare the object for use. Adding class
methods and their definitions occurs using a different this.firstName = firstName;
syntax described later in this article.
}
In the example below, the constructor of the class Person Person.prototype.sayHello = function() {
displays an alert when a Person is instantiated.
alert("Hello, I'm " + this.firstName);
function Person() { };
alert('Person instantiated'); var person1 = new Person("Alice");
} var person2 = new Person("Bob");
var person1 = new Person(); // call the Person sayHello method.
var person2 = new Person(); person1.sayHello(); // alerts "Hello, I'm Alice"
person2.sayHello(); // alerts "Hello, I'm Bob"
The Property (object attribute)
In JavaScript methods are regular function objects that
Properties are variables contained in the class; every are bound to an object as a property, which means they
instance of the object has those properties. Properties can be invoked "out of the context". Consider the following
should be set in the prototype property of the class example code:
(function) so that inheritance works correctly.
function Person(firstName) {
Working with properties from within the class is done using this.firstName = firstName;
the keyword this, which refers to the current object.
}
Accessing (reading or writing) a property outside of the
class is done with the syntax: InstanceName.Property; Person.prototype.sayHello = function() {
this is the same syntax used by C++, Java, and a number
alert("Hello, I'm " + this.firstName);
of other languages. (Inside the class the syntax
this.Property is used to get or set the property's value.)
};
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.100B 33

Copyright Free under CC BY Licence


var person1 = new Person("Alice"); // Add a couple of methods to Person.prototype
var person2 = new Person("Bob"); Person.prototype.walk = function(){
var helloFunction = person1.sayHello; alert("I am walking!");
person1.sayHello(); // alerts "Hello, I'm Alice" };
person2.sayHello(); // alerts "Hello, I'm Bob" Person.prototype.sayHello = function(){
helloFunction(); // alerts "Hello, I'm undefined" (or fails alert("Hello, I'm " + this.firstName);
// with a TypeError in strict mode) };
alert(helloFunction === person1.sayHello); // alerts // Define the Student constructor
true
function Student(firstName, subject) {
alert(helloFunction === Person.prototype.sayHello); //
// Call the parent constructor, making sure (using
alerts true
Function#call) that "this" is
helloFunction.call(person1); // alerts "Hello, I'm Alice"
// set correctly during the call
As that example shows, all of the references we have to Person.call(this, firstName);
the sayHello function - the one on person1, on
// Initialize our Student-specific properties
Person.prototype, in thehelloFunction variable, etc. - refer
to the same function. The value of this during a call to the this.subject = subject;
function depends on how we call it. In the common case };
when we call it in an expression where we got the function
from an object property - person1.sayHello() - this is set // Create a Student.prototype object that inherits from
to the object we got the function from (person1), which is Person.prototype.
why person1.sayHello() uses the name "Alice" and // Note: A common error here is to use "new Person()" to
person2.sayHello() uses the name "Bob". But if we call it create the Student.prototype.
other ways, this is set differently: Calling it from a variable
- helloFunction() - sets this to the global object (window, // That's incorrect for several reasons, not least that we
on browsers). Since that object (probably) doesn't have a don't have anything to
firstName property, we end up with "Hello, I'm undefined". // give Person for the "firstName" argument. The correct
(That's in loose mode code; it would be different [an error] place to call Person is
in strict mode, but to avoid confusion we won't go into
detail here.) Or we can set this explicitly using // above, where we call it from Student.
Function#call (or Function#apply), as shown at the end of Student.prototype = Object.create(Person.prototype); //
the example. See note below

Inheritance // Set the "constructor" property to refer to Student

Inheritance is a way to create a class as a specialized Student.prototype.constructor = Student;


version of one or more classes (JavaScript only supports // Replace the "sayHello" method
single inheritance). The specialized class is commonly
called the child, and the other class is commonly called Student.prototype.sayHello = function(){
the parent. In JavaScript you do this by assigning an alert("Hello, I'm " + this.firstName + ". I'm studying " +
instance of the parent class to the child class, and then this.subject + ".");
specializing it. In modern browsers you can also use
Object.create to implement inheritance. };
// Add a "sayGoodBye" method
JavaScript does not detect the child class
prototype.constructor (see Object.prototype), so we must Student.prototype.sayGoodBye = function(){
state that manually. alert("Goodbye!");

In the example below, we define the class Student as a };


child class of Person. Then we redefine the sayHello() // Example usage:
method and add thesayGoodBye() method.
var student1 = new Student("Janet", "Applied Physics");
// Define the Person constructor student1.sayHello(); // "Hello, I'm Janet. I'm studying
function Person(firstName) { Applied Physics."

this.firstName = firstName; student1.walk(); // "I am walking!"

} student1.sayGoodBye(); // "Goodbye!"

34 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.100B

Copyright Free under CC BY Licence


// Check that instanceof works correctly Abstraction
alert(student1 instanceof Person); // true
Abstraction is a mechanism that permits modeling the
alert(student1 instanceof Student); // true current part of the working problem. This can be achieved
by inheritance (specialization), or composition. JavaScript
Regarding the Student.prototype =
achieves specialization by inheritance, and composition
Object.create(Person.prototype); line: On older JavaScript
by letting instances of classes be the values of attributes
engines without Object.create, one can either use a
of other objects.
"polyfill" (aka "shim", see the linked article), or one can
use a function that achieves the same result, such as:
The JavaScript Function class inherits from the Object
function createObject(proto) { class (this demonstrates specialization of the model) and
the Function.prototype property is an instance of Object
function ctor() { }
(this demonstrates composition).
ctor.prototype = proto;
var foo = function(){};
return new ctor();
alert( 'foo is a Function: ' + (foo instanceof Function) );
}
// alerts "foo is a Function: true"
// Usage:
alert( 'foo.prototype is an Object: ' + (foo.prototype
Student.prototype = createObject(Person.prototype); instanceof Object) ); // alerts "foo.prototype is an Object:
true"
See Object.create for more on what it does, and a shim
for older engines. Polymorphism

Encapsulation Just like all methods and properties are defined inside the
prototype property, different classes can define methods
In the previous example, Student does not need to know with the same name; methods are scoped to the class in
how the Person class's walk() method is implemented, which they're defined. This is only true when the two
but still can use that method; the Student class doesn't classes do not hold a parent-child relation (when one does
need to explicitly define that method unless we want to not inherit from the other in a chain of inheritance).
change it. This is called encapsulation, by which every
class inherits the methods of its parent and only needs to
define things it wishes to change.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.100B 35

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.101A
COPA - JavaScript and creating Web page

String and number methods in JavaScript


Objectives : At the end of this lesson you shall be able to
• explain string
• explain different string methods.

JavaScript Strings Example 5

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.

Example 2 var tName = "Veni";

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");

String Lengthproperty JavaScript String Methods

The length of a string is found in the built in property length. String methods help you to work with strings.

Example 3 Finding a String in a String

var s= "Computer Operator and Programming Assistant"; indexOf() method


var slen = s.length;
The indexOf() method returns the index(position) of the
first occurrence of a specified text in a string:
Backslash escape character.
Example 7
The backslash (\) escape character turns special characters
into string characters.
var str = "When I do good I feel good ";
Code Result Description var num = str.indexOf("good");

\' ' Single quote Result:


\" " Double quote
The variable numhas the position value 10.
\\ \ Backslash
Note: JavaScript counts positions from zero.0 is
The sequence \" inserts a double quote in a string. the first position in a string, 1 is the second, 2 is
the third ...
Example 4
lastIndexOf() method
var x = "Bhubaneswar is known as the \"Temple City of
India\""; The lastIndexOf() method returns the index(position) of
the last occurrence of a specified text in a string.
The sequence \' inserts a single quote in a string:

36

Copyright Free under CC BY Licence


Example 8 Example 12

var str = "When I do good I feel good"; var str = "Hockey,Kabadi,Cricket";


var num = str.lastIndexOf("good"); var res = str.slice(14, 21);

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);

This example slices out a portion of a string from position Result:


14 to position 21.
The result of res will beKabadi
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101A 37

Copyright Free under CC BY Licence


If you omit the second parameter, substr() will slice out the Example 21
rest of the string.
str = " I like custard apple and apple";
Example 17
var newstr = str.replace(/apple/g, "Mango");
var str = "Hockey,Kabadi,Cricket";
Result:
var res = str.substr(7);
The result of newstr will be I like custard Mango and
Result: Mango

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();

str = "I like custard apple"; Result:


var newstr = str.replace("custard apple", "mango");
The result of str2 will be information technology
Result: The concat() Method
concat() joins two or more strings.
The result of newstr will be I like mango
Example 24
Note : The replace() method does not change
the string it is called on. It returns a new string. var txt1 = "Mr";
By default, the replace() function replaces only
the first match. var txt2 = "Selvaraj";
var txt3 = txt1.concat(".", txt2);
By default, the replace() function is case sensitive. Writing
CUSTARD APPLE (with upper-case) will not work. Result:
To replace case insensitive, use a regular expression with
an /i flag (insensitive). The result of txt3 will be Mr.Selvaraj
The concat() method can be used instead of the plus
Example 20 operator. These two lines do the same.
str = "I like custard apple"; Example 25
var newstr = str.replace(/CUSTARD APPLE/i, "Mango");
var txt = "Mr" + "." + "Selvaraj";
Result: var txt = "Mr".concat(".", "Selvaraj");
The result of newstr will be I like Mango String.trim()
Note that regular expressions are written without quotes. String.trim() removes whitespace from both sides of a
string.
To replace all matches, use a regular expression with a /
g flag (global match).

38 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101A

Copyright Free under CC BY Licence


Example 26 <script>
var str = "Temple";
var str = " India Gate ";
var arr = str.split("");
alert(str.trim());
var text = "";
Result:
var i;
India Gate is displayed without leading and trailing blank for (i = 0; i < arr.length; i++) {
spaces in alert box.
text += arr[i] + "<br>"
Extracting String Characters }
document.getElementById("demo").innerHTML = text;
The charAt() method returns the character at a specified
index in a string. </script>
</body>
Example 27
</html>
var str = "Thirumalai Nayakkar Mahal";
Result:
str.charAt(0); // returns T
T
The charCodeAt() method returns the unicode of the
e
character at a specified index in a string. The method
returns an UTF-16 cone integer between 0 and 65535. m
p
Example 28
l
var str = "Hill Station";
e
str.charCodeAt(0); // returns 72
?
Converting a String to an Array
JavaScript Number Methods
A string can be converted to an array with the split() Number methods help you work with numbers.
method.
Number Methods and Properties
Example 29
Primitive values like 2018 or 1.44 , cannot have properties
var txt1 = "Kovai,Nellai,Madurai"; // String and methods because they are not objects.

var txt2 = txt1.split(","); // Split on commas But with JavaScript, methods and properties are also
available to primitive values, because JavaScript treats
Result: primitive values as objects when executing methods and
properties.
The result of txt2 will be Kovai
The toString() Method
If the separator is omitted, the returned array will contain
the whole string in index [0].If the separator is "", the toString() returns a number as a string.All number methods
returned array will be an array of single characters. can be used on any type of numbers (literals, variables, or
expressions).
Example 30 Example 32

var txt = "Anaimai"; // String var n = 2018;


txt.split(""); // Split in characters n.toString(); // returns 2018 from variable x

Example 31 (2018).toString(); // returns 2018 from literal 2018


(2000+18).toString(); // returns 2018 from expression
<!DOCTYPE html> 2000 + 18
<html>
The toExponential() Method
<body>
toExponential() returns a string, with a number rounded
<p id="demo"></p> and written using exponential notation.A parameter defines
the number of characters behind the decimal point.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101A 39

Copyright Free under CC BY Licence


Example 33 1 The Number() method
2 The parseInt() method
var x = 3. 869;
3. The parseFloat() method
x.toExponential(2); // returns 3.87e+0
x.toExponential(4); // returns 3.8690e+0 These methods are not number methods, but global
JavaScript methods.
x.toExponential(6); // returns 3.869000e+0
Global JavaScript Methods
The parameter is optional. If you don't specify it, JavaScript
will not round the number.
JavaScript global methods can be used on all JavaScript
data types.These are the most relevant methods, when
The toFixed() Method
working with numbers.
toFixed() returns a string, with the number written with a
Method Description
specified number of decimals.
Number() Returns a number, converted from its
Example 34
argument.
var x = 3. 869; parseInt() Parses its argument and returns an
integer
x.toFixed(0); // returns 4
parseFloat() Parses its argument and returns a
x.toFixed(2); // returns 3.87
floating point number
x.toFixed(4); // returns 3.8690
x.toFixed(6); // returns 3.869000 The Number() Method
Number() can be used to convert JavaScript variables to
Note : toFixed(2) is perfect for working with numbers.
money.
Example 37
The toPrecision() Method
Number(true); // returns 1
toPrecision() returns a string, with a number written with Number(false); // returns 0
a specified length.
Number("25"); // returns 25
Example 35 Number(" 25"); // returns 25

var x = 3. 869; Number("25 "); // returns 25

x.toPrecision(); // returns 3. 869 Number(" 25 "); // returns 25

x.toPrecision(2); // returns 3.9 Number("25.77"); // returns 25.77

x.toPrecision(4); // returns 3. 869 Number("25,77"); // returns NaN

x.toPrecision(6); // returns 3. 86900 Number("2577"); // returns NaN

The valueOf() Method Number("ITI"); // returns NaN

valueOf() returns a number as a number. Note : If the number cannot be converted, NaN
(Not a Number) is returned.
Example 36
The Number() Method Used on Dates. Number() can also
var x = 451; convert a date to a number:
x.valueOf(); // returns 451 from variable x Example 38
(451).valueOf(); // returns 451 from literal 451 Number(new Date("2018-09-15")); // returns
(400 + 51).valueOf(); // returns 451 from expression 400 1536969600000
+ 51
Note : The Number() method above returns the
Converting Variables to Numbers number of milliseconds since 1.1.1970.

There are 3 JavaScript methods that can be used to convert The parseInt()Method
variables to numbers: parseInt() parses a string and returns a whole number.
Spaces are allowed. Only the first number is returned.

40 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101A

Copyright Free under CC BY Licence


Example 39 Example 42

parseInt("25"); // returns 25 var n = Number.MIN_VALUE;


parseInt("25.33"); // returns 25
Result:
parseInt("25 20 30"); // returns 25
MIN_VALUE returns the smallest number possible in
parseInt("25 years"); // returns 25
JavaScript.
parseInt("years 25"); // returns NaN
5e-324
Try it yourself " JavaScript POSITIVE_INFINITY

If the number cannot be converted, NaN (Not a Number) is Example 43


returned.
var n = Number.POSITIVE_INFINITY;
The parseFloat() Method
POSITIVE_INFINITY is returned on overflow.
parseFloat() parses a string and returns a number. Spaces
are allowed. Only the first number is returned: Example 44

Example 40 var n = 2 / 0;
JavaScript NEGATIVE_INFINITY
parseFloat("25"); // returns 25
parseFloat("25.77"); // returns 25.77 Example 45
parseFloat("255075"); // returns 25
var n = Number.NEGATIVE_INFINITY;
parseFloat("25 years"); // returns 25
NEGATIVE_INFINITY is returned on overflow:
parseFloat("years 25"); // returns NaN
Example 46
Note : If the number cannot be converted, NaN
(Not a Number) is returned. var x = -1 / 0;
JavaScript NaN - Not a Number
?
Example 47
Number Properties
var x = Number.NaN;
Property Description
NaN is a JavaScript reserved word indicating that a number
MIN_VALUE Returns the smallest number
is not a legal number.Trying to do arithmetic with a non-
possible in JavaScript
numeric string will result in NaN (Not a Number).
MAX_VALUE Returns the largest number
possible in JavaScript Example 48

POSITIVE_INFINITY Represents infinity (returned on var n = 500 / "Price"; // n will be NaN (Not a Number)
overflow)
Number Properties Cannot be Used on Variables
NEGATIVE_INFINITY Represents negative infinity
(returned on overflow) Number properties belongs to the JavaScript's number
object wrapper called Number.These properties can only
NaN Represents a "Not-a-Number" be accessed as Number.MAX_VALUE.
value
Using newNumber.MAX_VALUE, where 'newNumber' is a
JavaScript MIN_VALUE and MAX_VALUE variable, expression, or value, will return undefined.
Example 41 Example 49
var n = Number.MAX_VALUE; var a = 10;
Result: var b = a.MAX_VALUE; // b becomes undefined
MAX_VALUE returns the largest possible number in
JavaScript.
1.7976931348623157e+308
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101A 41

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.101B
COPA - JavaScript and creating Web page

Math objects in JavaScript


Objectives : At the end of this lesson you shall be able to
• explain Math objects in Java Script.

JavaScript Math Object Angle in radians = Angle in degrees x PI / 180.

The JavaScript Math object allows you to perform Example 7


mathematical tasks on numbers.
Math.sin(90 * Math.PI / 180); // returns 1 (the sine of 90
Math.PI; // returns 3.141592653589793 degrees)

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)

Example 1 Math.cos(x) returns the cosine (a value between -1 and 1)


of the angle x (given in radians).
Math.round(5.8); // returns 6
If you want to use degrees instead of radians, you have to
Math.round(5.4); // returns 5 convert degrees to radians:

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

Math.pow(5, 2); // returns 25 Math.cos(0 * Math.PI / 180); // returns 1 (the cos of 0


degrees)
Math.sqrt(x) returns the square root of x:
Math.min() and Math.max() can be used to find the lowest
Example 3 or highest value in a list of arguments:

Math.sqrt(25); // returns 5 Example 9

Math.abs(x) returns the absolute (positive) value of x: Math.min(20,40,6,0,-10); // returns -10

Example 4 Example 10

Math.abs(-3.5); // returns 3.5 Math.max(20,40,6,0,-10); // returns 40

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

Math.ceil(5.4); // returns 6 Math.random(); // returns a random number


Math.floor(x) returns the value of x rounded down to its
nearest integer: Math Properties (Constants)

JavaScript provides 8 mathematical constants that can be


Example 6
accessed with the Math object:
Math.floor(5.8); // returns 5
Example 12
Math.sin(x) returns the sine (a value between -1 and 1) of
Math.E // returns Euler's number
the angle x (given in radians).
Math.PI // returns PI
If you want to use degrees instead of radians, you have to
convert degrees to radians.
Math.SQRT2 // returns the square root of 2

42

Copyright Free under CC BY Licence


Math.SQRT1_2 // returns the square root of 1/2 Math Constructor

Math.LN2 // returns the natural logarithm of 2 Unlike other global objects, the Math object has no
constructor. Methods and properties are static. All
Math.LN10 // returns the natural logarithm of 10 methods and properties (constants) can be used without
creating a Math object first.
Math.LOG2E // returns base 2 logarithm of E

Math.LOG10E // returns base 10 logarithm of E

Math Object Methods

Method Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x, in radians

asin(x) Returns the arcsine of x, in radians

atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2
radians

atan2(y, x) Returns the arctangent of the quotient of its arguments

ceil(x) Returns the value of x rounded up to its nearest integer

cos(x) Returns the cosine of x (x is in radians)

exp(x) Returns the value of Ex

floor(x) Returns the value of x rounded down to its nearest integer

log(x) Returns the natural logarithm (base E) of x

max(x, y, z, ..., n) Returns the number with the highest value

min(x, y, z, ..., n) Returns the number with the lowest value

pow(x, y) Returns the value of x to the power of y

random() Returns a random number between 0 and 1

round(x) Returns the value of x rounded to its nearest integer

sin(x) Returns the sine of x (x is in radians)

sqrt(x) Returns the square root of x

tan(x) Returns the tangent of an angle

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101B 43

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.101C
COPA - JavaScript and creating Web page

JavaScript Dates
Objectives : At the end of this lesson you shall be able to
• explain JavaScript Date Objects
• explain JavaScript Date Formats
• explain JavaScript Date get methods
• explain JavaScript Date set methods.

JavaScript Date Objects 2 new Date(year, month, ...)

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.

Thu Sep 27 2018 09:09:39 GMT+0530 (India Standard Example 2


Time)
var d = new Date(2018, 06, 30, 09, 10, 25, 0);
Creating Date Objects
7 numbers specify year, month, day, hour, minute, sec-
Date objects are created with the new Date() constructor. ond, and millisecond (in that order).

There are 4 ways to create a new date object. They are Result: (Fig 2)

1 new Date() Fig 2

2 new Date(year, month, day, hours, minutes, seconds,


milliseconds)
3 new Date(date string)
4 new Date(milliseconds)

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

var d = new Date(2018, 06, 30, 09, 10, 25);

5 numbers specify year, month, day, hour, and minute.

Example 4

var d = new Date(2018, 06, 30, 09, 10);

Example 5

var d = new Date(2018, 06, 30, 09);

Note Date objects are static. The computer time 3 numbers specify year, month, and day.
is ticking, but date objects are not.

44

Copyright Free under CC BY Licence


Example 6
Note: JavaScript stores dates as number of mil-
var d = new Date(2018, 06, 30); liseconds since January 01, 1970, 00:00:00 UTC
(Universal Time Coordinated). Zero time is
2 numbers specify year and month. January 01, 1970 00:00:00 UTC. Now the time
is: 1537962903199 milliseconds past January 01,
Example 7 1970

var d = new Date(2018, 06); 4 new Date(milliseconds)

Result: (Fig 3) new Date(milliseconds) creates a new date object as zero


time plus milliseconds.
Fig 3
Example 11

var d = new Date(0);

01 January 1970 plus 100 000 000 milliseconds is ap-


proximately 02 January 1970.

Example 12

var d = new Date(100000000);

You cannot omit month. If you supply only one parameter Result: (Fig 5)
it will be treated as milliseconds. Fig 5

Example 8

var d = new Date(2018);

Previous Century

One and two digit years will be interpreted as 19xx.

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);

Example 10 Result: (Fig 6)

Fig 6
var d = new Date("December 20, 2018 10:15:00");

Result: (Fig 4)

Fig 4

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C 45

Copyright Free under CC BY Licence


The toDateString() method converts a date to a more read-
Example 14
able format.
var d = new Date(86400000);
Example 17
Result:
var d = new Date();
Fri Jan 02 1970 05:30:00 GMT+0530 (India Standard Time)
alert(d.toDateString());
Note: Using new Date(milliseconds), creates a
new date object as January 1, 1970, 00:00:00
Result: (Fig 8)
Universal Time (UTC) plus the milliseconds.
One day (24 hours) is 86 400 000 milliseconds. Fig 8

Date Methods

When a Date object is created, a number of methods al-


low you to operate on it. Date methods allow you to get
and set the year, month, day, hour, minute, second, and
millisecond of date objects, using either local time or UTC
(universal, or GMT) time.

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

var d = new Date("2002-06-30");

Note: The computed date will be relative to


your time zone. Depending on your time zone,
the result above will vary between June 29 and
June 30.

ISO Dates (Year and Month)

ISO dates can be written without specifying the day (YYYY-


MM).

46 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C

Copyright Free under CC BY Licence


Example 19 JavaScript Long Dates

var d = new Date("2002-06"); Long dates are most often written with a "MMM DD YYYY"
syntax like this.
Result:
Example 23
Sat Jun 01 2002 05:30:00 GMT+0530 (India Standard Time)
var d = new Date("Aug 31 2012");
ISO Dates (Only Year)
Month and day can be in any order.
ISO dates can be written without month and day (YYYY).
Example 24
Example 20
var d = new Date("31 Aug 2012");
var d = new Date("2011");
And, month can be written in full (January), or abbreviated
(Jan).
Result:
Example 25
Sat Jan 01 2011 05:30:00 GMT+0530 (India Standard Time)
var d = new Date("August 31 2012");
ISO Dates (Date-Time)
var d = new Date("AUGUST 31 2012");
ISO dates can be written with added hours, minutes, and
seconds (YYYY-MM-DDTHH:MM:SSZ) Note: Commas are ignored. Names are case
insensitive.
Example 21
Date Input - Parsing Dates
var d = new Date("2011-12-20T12:00:00Z");
If you have a valid date string, you can use the Date.parse()
Result: method to convert it to milliseconds. Date.parse() returns
the number of milliseconds between the date and
Tue Dec 20 2011 17:30:00 GMT+0530 (India Standard Time) January 1, 1970.

Note: Date and time is separated with a capi- Example 26


tal T. UTC time is defined with a capital
letter Z. var msec = Date.parse("Sep 15, 1996");

JavaScript Short Dates. document.getElementById("demo").innerHTML = msec;

Short dates are written with an "MM/DD/YYYY" syntax Result:


like this.
842725800000
Example 22
You can then use the number of milliseconds to convert it
var d = new Date("06/30/2002"); to a date object.

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

These methods can be used for getting information from a


date object.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C 47

Copyright Free under CC BY Licence


Fig 10
Method Description

getFullYear() Get the year as a four digit number


(yyyy)

getMonth() Get the month as a number (0-11)

getDate() Get the day as a number (1-31)

getHours() Get the hour (0-23)

getMinutes() Get the minute (0-59)


The getMonth() Method
getSeconds() Get the second (0-59)
The getMonth() method returns the month of a date as a
getMilliseconds() Get the millisecond (0-999) number (0-11).
getTime() Get the time (milliseconds since Example 30
January 1, 1970)

getDay() Get the weekday as a number var d = new Date();


(0-6)
document.getElementById("demo").innerHTML =
Date.now() Get the time. ECMAScript 5. d.getMonth();

The getTime() Method Result: (Fig 11)


Fig 11
The getTime() method returns the number of milliseconds
since January 1, 1970.

Example 28

var d = new Date();

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

var d = new Date();


var months = ["January", "February", "March", "April",
"May", "June", "July", "August", "September", "October",
"November", "December"];
The getFullYear() Method document.getElementById("demo").innerHTML =
months[d.getMonth()];
The getFullYear() method returns the year of a date as a
Result: (Fig 12)
four digit number.
Fig 12
Example 29

var d = new Date();

alert(d.getFullYear());

Result: (Fig 10)

48 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C

Copyright Free under CC BY Licence


The getDate() Method Fig 15

The getDate() method returns the day of a date as a num-


ber (1-31).

Example 32

var d = new Date();

alert(d.getDate());

Result: (Fig 13)


The getSeconds() Method
Fig 13
The getSeconds() method returns the seconds of a date
as a number (0-59).

Example 35

var d = new Date();

alert(d.getSeconds());

The getHours() Method Result: (Fig 16)

Fig 16
The getHours() method returns the hours of a date as a
number (0-23).

Example 33

var d = new Date();

alert(d.getHours());

Result: (Fig 14)


Fig 14
The getMilliseconds() Method

The getMilliseconds() method returns the milliseconds of


a date as a number (0-999).

Example 36

var d = new Date();

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

var d = new Date();

alert(d.getMinutes());

Result: (Fig 15)

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C 49

Copyright Free under CC BY Licence


The getDay() Method
Method Description
The getDay() method returns the weekday of a date as a
getUTCDate() Same as getDate(), but returns
number (0-6).
the UTC date
Example 37
getUTCDay() Same as getDay(), but returns
the UTC day
var d = new Date();
getUTCFullYear() Same as getFullYear(), but
alert(d.getDay());
returns the UTC year
Result: (Fig 18)
getUTCHours() Same as getHours(), but returns
Fig 18 the UTC hour

getUTCMilliseconds() Same as getMilliseconds(), but


returns the UTC milliseconds

getUTCMinutes() Same as getMinutes(), but re


turns the UTC minutes

getUTCMonth() Same as getMonth(), but returns


the UTC month

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.

var d = new Date();


Set Date Methods
var days = ["Sunday", "Monday", "Tuesday", "Wednes-
day", "Thursday", "Friday", "Saturday"]; Set Date methods are used for setting a part of a date.

alert(days[d.getDay()]); Method Description

Result: (Fig 19) setDate() Set the day as a number (1-31)


Fig 19 setFullYear() Set the year (optionally month
and day)

setHours() Set the hour (0-23)

setMilliseconds() Set the milliseconds (0-999)

setMinutes() Set the minutes (0-59)

setMonth() Set the month (0-11)

setSeconds() Set the seconds (0-59)


UTC Date Methods
setTime() Set the time (milliseconds since
UTC date methods are used for working with UTC dates January 1, 1970)
(Universal Time Zone dates).
The setFullYear() Method

The setFullYear() method sets the year of a date object.


In this example to 2020.

50 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C

Copyright Free under CC BY Licence


Example 39 d.setMonth(2);

<script> alert(d);
var d = new Date();
</script>
d.setFullYear(2020);
Result: (Fig 22)
alert(d);
Fig 22
</script>

Result: (Fig 20)


Fig 20

The setDate() Method

The setDate() method sets the day of a date object (1-31).

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

The setDate() method can also be used to add days to a


date.

Note: month counts from 0. December is Example 43


month 11
<script>
The setMonth() Method
var d = new Date();
The setMonth() method sets the month of a date object
(0-11). d.setDate(d.getDate() + 25);

Example 41 alert(d);

<script> </script>

var d = new Date();


IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C 51

Copyright Free under CC BY Licence


Result: (Fig 24) Result: (Fig 26)
Fig 24 Fig 26

If adding days, shifts the month or year, the changes are The setSeconds() Method
handled automatically by the Date object.
The setSeconds() method sets the seconds of a date ob-
ject (0-59).
The setHours() Method
Example 46
The setHours() method sets the hours of a date object
(0-23).
<script>
Example 44 var d = new Date();
d.setSeconds(20);
<script>
alert(d);
var d = new Date();
</script>
d.setHours(20);
Result: (Fig 27)
alert(d); Fig 27

</script>
Result: (Fig 25)
Fig 25

Compare Dates
Dates can easily be compared.
The following example compares today's date with Janu-
ary 14, 2100.
The setMinutes() Method
Example 47
The setMinutes() method sets the minutes of a date ob-
var date1 = new Date(2010, 00, 15); //Year, Month, Date
ject (0-59).
var date2 = new Date(2011, 00, 15); //Year, Month, Date
Example 45
if (date1 > date2)
<script> {
var d = new Date(); alert("Date One is greather then Date Two.");
}
d.setMinutes(15);
else
alert(d);
{
</script> alert("Date Two is greather then Date One.");
}

52 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.102A
COPA - JavaScript and creating Web page

Document Object Model and Open source software


Objectives : At the end of this lesson you shall be able to
• define DOM
• explain DOM methods
• explain DOM documents
• describe HTML DOM elements
• explain HTML DOM events
• know Open Source Software

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:

When a web page is loaded, the browser creates a


Document Object Model of the page.

• JavaScript can change all the HTML elements in the DOM


page.
• JavaScript can change all the HTML attributes in the The DOM is a W3C (World Wide Web Consortium)
page standard.

• JavaScript can change all the CSS styles in the page The DOM defines a standard for accessing documents:
• JavaScript can remove existing HTML elements and
attributes "The W3C Document Object Model (DOM) is a platform
and language-neutral interface that allows programs and
• JavaScript can add new HTML elements and attributes scripts to dynamically access and update the content,
• JavaScript can react to all existing HTML events in the structure, and style of a document."
page

53

Copyright Free under CC BY Licence


The W3C DOM standard is separated into 3 different parts: <html>
<body>
• Core DOM - standard model for all document types
<p id="demo"></p>
• XML DOM - standard model for XML documents
<script>
• HTML DOM - standard model for HTML documents
document.getElementById("demo").innerHTML =
What is the HTML DOM? "Welcome to JavaScript!";
</script>
The HTML DOM is a standard object model and
programming interface for HTML. It defines: </body>
</html>
• The HTML elements as objects
In the example above, getElementById is a method, while
• The properties of all HTML elements
innerHTML is a property.
• The methods to access all HTML elements
The getElementById Method
• The events for all HTML elements
In other words: The HTML DOM is a standard for how to The most common way to access an HTML element is to
get, change, add, or delete HTML elements. use the id of the element. In the example above the
getElementById method used id="demo" to find the
HTML DOM Methods element.

HTML DOM methods are actions you can perform (on The innerHTML Property
HTML Elements)
The easiest way to get the content of an element is by
HTML DOM properties are values (of HTML Elements) using the innerHTML property. The innerHTML property is
that you can set or change. useful for getting or replacing the content of HTML elements.

The DOM Programming Interface Note: The innerHTML property can be used to
get or change any HTML element, including
The HTML DOM can be accessed with JavaScript (and <html> and <body>.
with other programming languages).
HTML DOM Document
In the DOM, all HTML elements are defined as objects.The
programming interface is the properties and methods HTML DOM document object
of each object. A property is a value that you can get or
set (like changing the content of an HTML element). A The document object is the owner of all other objects in
method is an action you can do (like add or deleting an your web page. In the HTML DOM object model, the
HTML element). document object represents your web page. If you want to
access objects in an HTML page, you always start with
Example 1 accessing the document object.

The following example changes the content (the innerHTML) Below are some examples of how you can use the
of the <p> element with id="demo": document object to access and manipulate HTML.

Finding HTML Elements

Method Description

document.getElementById() Find an element by element id

document.getElementsByTagName() Find elements by tag name

document.getElementsByClassName() Find elements by class name

54 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A

Copyright Free under CC BY Licence


Changing HTML Elements

Method Description

element.innerHTML= Change the inner HTML of an element

element.attribute= Change the attribute of an HTML element

element.setAttribute(attribute,value) Change the attribute of an HTML element

element.style.property= Change the style of an HTML element

Adding and Deleting HTML Elements

Method Description

document.createElement() Create an HTML element

document.removeChild() Remove an HTML element

document.appendChild() Add an HTML element

document.replaceChild() Replace an HTML element

document.write(text) Write into the HTML output stream

Adding Events handlers

Method Description

document.getElementById(id).onclick=function(){code} Adding event handler code to an onclick event

JavaScript HTML DOM Elements If the element is found, the method will return the element
as an object (in x).
Finding HTML Elements
If the element is not found, x will contain null.
Often, with JavaScript, you want to manipulate HTML Finding HTML Elements by Tag Name
elements.
This example finds the element with id="main", and then
To do so, you have to find the elements first. There are a finds all <p> elements inside "main":
couple of ways to do this:
Example 3
• Finding HTML elements by id
var x = document.getElementById("main");
• Finding HTML elements by tag name
var y = x.getElementsByTagName("p");
• Finding HTML elements by class name
Finding HTML Elements by Class Name
• Finding HTML elements by HTML object collections
If you want to find all HTML elements with the same class
Finding HTML Elements by Id name, use this method get ElementsByClassName()
The easiest way to find HTML elements in the DOM, is by Example 4
using the element id.
document.getElementsByClassName("intro");
This example finds the element with id="demo":
The example above returns a list of all elements with
Example 2 class="intro".
var x = document.getElementById("demo"); Note: Finding elements by class name does not
work in Internet Explorer 5,6,7, and 8.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A 55

Copyright Free under CC BY Licence


Finding HTML Elements by HTML Object Collections

This example finds the form element with id="frm1", in the


forms collection, and displays all element values:

Method Description DOM

document.anchors Returns all <a> with a value in the name attribute 1


document.applets Returns all <applet> elements (Deprecated in HTML5) 1
document.baseURI Returns the absolute base URI of the document 3
document.body Returns the <body> element 1
document.cookie Returns the document's cookie 1
document.doctype Returns the document's doctype 3
document.documentElement Returns the <html> element 3
document.documentMode Returns the mode used by the browser 3
document.documentURI Returns the URI of the document 3
document.domain Returns the domain name of the document server 1
document.domConfig Returns the DOM configuration 3
document.embeds Returns all <embed> elements 3
document.forms Returns all <form> elements 1
document.head Returns the <head> element 3
document.images Returns all <image> elements 1
document.implementation Returns the DOM implementation 3
document.inputEncoding Returns the document's encoding (character set) 3
document.lastModified Returns the date and time the document was updated 3
document.links Returns all <area> and <a> elements value in href 1
document.readyState Returns the (loading) status of the document 3
document.referrer Returns the URI of the referrer (the linking document) 1
document.scripts Returns all <script> elements 3
document.strictErrorChecking Returns if error checking is enforced 3
document.title Returns the <title> element 1
document.URL Returns the complete URL of the document 1

Example 5 • document.anchors

var x = document.getElementById("frm1"); • document.body


• document.documentElement
var text = "";
• document.embeds
var i;
• document.forms
for (i = 0; i < x.length; i++) {
• document.head
text += x.elements[i].value + "<br>"; • document.images
} • document.links
document.getElementById("demo").innerHTML = text; • document.scripts
• document.title
The following HTML objects (and object collections) are
also accessible:
The HTML DOM allows JavaScript to change the content
of HTML elements.

56 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A

Copyright Free under CC BY Licence


Changing the HTML Output Stream Example 8

JavaScript can create dynamic HTML content. In <!DOCTYPE html>


JavaScript, document.write() can be used to write directly
<html>
to the HTML output stream.
<body>
Example 6
<h1 id="id1">Old Heading</h1>
<!DOCTYPE html> <script>
<html> var element = document.getElementById("id1");
<body> element.innerHTML = "New Heading";
<script> </script>
document.write(Date()); </body>
</script> </html>
</body>
Example explained:
</html>
• The HTML document above contains an <h1> element
Note: Never use document.write() after the with id="id1"
document is loaded. It will overwrite the
• We use the HTML DOM to get the element with id="id1"
document.
• A JavaScript changes the content (innerHTML) of that
Changing HTML Content element to "New Heading"

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.

document.getElementById(id).innerHTML = new HTML document.getElementById(id).attribute = new value

This example changes the content of a <p> element: This example changes the value of the src attribute of an
<img> element.
Example 7
Example 9
<html>
<!DOCTYPE html>
<body>
<html>
<p id="p1">Hello World!</p>
<body>
<script>
<img id="Image1" src="flower.gif">
document.getElementById("p1").innerHTML = "New text!";
<script>
</script> document.getElementById("Image1").src =
"newflower.jpg";
</body>
</script>
</html>
</body>
Example explained:
</html>
• The HTML document above contains a <p> element
Example explained:
with id="p1"
• We use the HTML DOM to get the element with id="p1" • The HTML document above contains an <img> element
with id="myImage"
• A JavaScript changes the content (innerHTML) of that
element to "New text!" • We use the HTML DOM to get the element with
id="myImage"
This example changes the content of an <h1> element:
• A JavaScript changes the src attribute of that element
from "smiley.gif" to "landscape.jpg"

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A 57

Copyright Free under CC BY Licence


Changing HTML Style A JavaScript can be executed when an event occurs, like
when a user clicks on an HTML element. To execute code
To change the style of an HTML element, use this syntax. when a user clicks on an element, add JavaScript code to
an HTML event attribute
document.getElementById(id).style.property = new style
onclick=JavaScript
The following example changes the style of a <p> element:
Examples of HTML events:
Example 10
• When a user clicks the mouse
<html>
• When a web page has loaded
<body>
• When an image has been loaded
<p id="p2">Hello World!</p>
• When the mouse moves over an element
<script>
• When an input field is changed
document.getElementById("p2").style.color = "green";
• When an HTML form is submitted
</script>
• When a user strokes a key
<p>The paragraph above was changed by a script.</p>
</body> In this example, the content of the <h1> element is
changed when a user clicks on it.
</html>
Example 12
Using Events
<!DOCTYPE html>
The HTML DOM allows you to execute code when an
event occurs. Events are generated by the browser when <html>
"things happen" to HTML elements. <body>
<h1 onclick="this.innerHTML = 'Ooops!'">Click on this
• An element is clicked on
text!</h1>
• The page has loaded
</body>
• Input fields are changed
</html>
This example changes the style of the HTML element with
HTML Event Attributes
id="id1", when the user clicks a button.
To assign events to HTML elements you can use event
Example 11
attributes.
<!DOCTYPE html>
Example 13
<html>
Assign an onclick event to a button element:
<body>
<button onclick="displayDate()">Try it</button>
<h1 id="id1">Heading1</h1>
<button type="button" In the example above, a function named displayDate will
onclick="document.getElementById('id1').style.color = be executed when the button is clicked.
'blue'">
Assign Events Using the HTML DOM
Click Me</button>
The HTML DOM allows you to assign events to HTML
</body> elements using JavaScript.
</html> Example 14

JavaScript HTML DOM Events Assign an onclick event to a button element:


<script>
HTML DOM allows JavaScript to react to HTML events.
document.getElementById("myBtn").onclick =
Reacting to Events displayDate;

</script>

58 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A

Copyright Free under CC BY Licence


In the example above, a function named displayDate is DOM Event Listener
assigned to an HTML element with the id="myBtn".
The addEventListener() method
The function will be executed when the button is clicked.
Add an event listener that fires when a user clicks a button.
The onload and onunload Events
Example 17
The onload and onunload events are triggered when the
user enters or leaves the page. The onload event can be <!DOCTYPE html>
used to check the visitor's browser type and browser
version and load the proper version of the web page based <html>
on the information.The onload and onunload events can
be used to deal with cookies. <body>

Example 15 <h2>JavaScript addEventListener()</h2>

<body onload="checkCookies()"> <p>This example uses the addEventListener() method to


attach a click event to a button.</p>
The onchange Event
<button id="myBtn">Try it</button>
The onchange event is often used in combination with
validation of input fields.Below is an example of how to <p id="demo"></p>
use the onchange. The upperCase() function will be called
when a user changes the content of an input field. <script>

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.

onmousedown and onmouseup

Change an image when a user holds down the mouse


button.

onload

Display an alert box when the page has finished loading.


• The addEventListener() method attaches an event
onfocus handler to the specified element.
• The addEventListener() method attaches an event
Change the background-color of an input field when it gets handler to an element without overwriting existing event
focus. handlers.
Mouse Events • You can add many event handlers to one element.
• You can add many event handlers of the same type to
Change the color of an element when the cursor moves one element, i.e two "click" events.
over it.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A 59

Copyright Free under CC BY Licence


• You can add event listeners to any DOM object not 1 WordPress
only HTML elements. i.e the window object.
The official websites for WordPress are
• The addEventListener() method makes it easier to
https://wordpress.com and
control how the event reacts to bubbling.
https://wordpress.org/.
• When using the addEventListener() method, the
JavaScript is separated from the HTML markup, for
2 Kompozer
better readability and allows you to add event listeners
even when you do not control the HTML markup. The official website for Kompozer is
• You can easily remove an event listener by using the https://www.kompozer.net.
removeEventListener() method.
3 Joomla
Open Source Software The official website for Joomla is
You can build a website using these popular free and open https://www.joomla.org/.
source website building tools. Nowadays, whether you
are an individual entrepreneur or representing a business 4 Drupal
organisation, a website is a must for personal and The official website for Drupal is
professional growth. Organisations are spending lots of
money to build attractive websites. The following are some https://www.drupal.org/.
of the open source website building tools that you can
use to build your website on your own, without much 5 OpenCms
knowledge about programming or the Internet.
The official website for OpenCms is
http:// www.opencms.org/en/.

60 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.102B
COPA - JavaScript and creating Web page

Develop and edit web pages in KompoZer


Objectives : At the end of this lesson you shall be able to
• know introduction to KompoZer
• know develop and edit web pages
• know the use of templates
• explain Publishing web sites
• describe Site Manager
• know preferences
• explain publishing web sites.

Introduction application window. Many editing functions are very similar


to those in a word processor. The top four toolbars on the
What is KompoZer? KompoZer application window provide a number of editing
functions - to see what any do hover the cursor over an item
KompoZer is a complete Web Authoring System which and a hint will appear.
integrates web page development and web file management.
It provides a web page editor which has a simple graphical Saving a Page To save a page: On the Composition toolbar
(WYSIWYG - what you see is what you get) interface. With click 'Save'. If it was a new document a dialog window will
KompoZer, newcomers will quickly and easily be able to ask you to enter a title for the page. This will appear in the
produce new web pages. The output code is compliant to tab at the top of the page display area. NB this is NOT the
a high extent with the latest issues of the appropriate web file name. Click 'OK'; you will then be offered a normal save
language specifications window which allows you to browse to a suitable location
and name the file. The file extension offered will be HTML.
KompoZer incorporates a Site Manager; this gives rapid
access to the files on both local machines and remote Browsing a page :To see how your page will look in your
servers. It can cater for several sites and switch rapidly default browser on the Composition toolbar click 'Browse'.
between them. From within KompoZer pages and associated
files may be uploaded to a remote server. KompoZer Help: The help system should be a first resort in case of
supports the use of "Styles" through Cascading Style need. The forum at http://wysifauthoring.informe.com/ is a
sheets (CSS) both embedded and external. It has an editor place for sharing experiences and obtaining and giving
which generates CSS code conforming with CSS 2.1 help. Many of the contributors are users of the programs
specifications. and range from beginners to those with lots of experience.

Who is KompoZer for? Develop and edit Web pages

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 :

Open KompoZer. The main window opens. At the top are


a number of toolbars. The topmost is the Menu Bar. This
carries a number of items (File, Editetc) used to make
selections. The next is the 'Composition Toolbar' which
carries a number of 'Buttons' labelled 'New', 'Open' etc.

To create a new page: On the Composition toolbar Click the


'New' button.

To open an existing page:Assuming that the page is stored


on your local disk in HTML format: On the menu Bar click
'File' then 'Open File'. Browse to the file and click 'Open'.

Editing a web page: Your web page - blank or otherwise -


is in the large pane in the centre right of the KompoZer

61

Copyright Free under CC BY Licence


When KompoZer starts the window carries a menu bar To open an existing page
across the top (File, Edit, View etc). Below this are three
'Toolbars'. To ensure that everything is visible, on the Menu 1 Click the OPEN button to access a normal browse
bar selectView > Show/Hide and see that each of the dialogue.
following is checked: 2 Click File > Recent Pages to get rapid access to those
recently worked on.
• Composition Toolbar,
3 Or use the Site Manager which provides a powerful mini-
• Format Toolbar 1
browser and is very easily set up. The Doctype of an
• Format Toolbar 2 existing page will remain the same as before it was
opened. It cannot be changed in KompoZer.
• Edit Mode Toolbar
• Status bar Each page opened starts in a new tab which can be clicked
to select a document to work on.
• Rulers
• Site Manager Editing in KompoZer

The three toolbars across the top of the window carry KompoZer supports all the standard Windows editing
buttons (represented by icons). Hover on any to find its commands and shortcut keys. e.g. Copy Ctrl+C, Paste
function. If any are greyed out they are not functional in the Ctrl+V etc. There are other KompoZer specifics. These are
current mode as they are context sensitive. Across the great time savers. In 'HTML Tags' view KompoZer supports
centre of the window are two panes: the 'Site Manager' on drag and drop editing for block items. (Select an item by
the left and a blank web page on the right. The Site Manager pressing the Control key while clicking on the Tag.) An
is a powerful tool. Since it is not needed yet it may be extreme time saver is KompoZer's double click response.
closed by clicking on its close button or pressing F9. At the In several cases, such as links, images and tables, a very
top of the Page area there is a Page tab which carries the useful editing window is opened. KompoZer supports many
name of the page ('Untitled'). KompoZer Help refers to this levels of Undo and Redo, however changes made in
as the 'Tab Browser' toolbar. If you had several pages open, 'Source' view cannot be undone after you have changed the
as shown in the Fig.1, this tab would allow you to select one view.
them rapidly. At the bottom of the page area is the 'Edit
Mode Toolbar' which carries four tabs which select one of Saving files
four 'Viewing modes' for a page ('Normal', 'HTML Tags',
'Source', 'Preview'.) Go to File > Save as. You are offered a 'Save Page as'
window which allows you to browse to the folder you want
At the bottom of the window is the 'Status Bar'. This is a very to use. You will find the file name already completed with
powerful tool. Once a page is populated, by clicking any your page title. You will probably want to changethis to a
item in the page area its structure appears on the status shorter, all lower case, name. You will find the file extension
bar. Any class or id applied to an element is shown and any completed as 'html' you may prefer to, and may alter it to
bearing an inline style isindicated in italic type. Hovering "htm".
reveals the style declaration. Additionally clicking an
element marker highlights the element in both normal view Printing pages
and, on changing view, in source view thus simplifying
navigation in source view. Note The figure shows the The 'Print' button allows you to print the current page to a
buttons as they appear when KompoZer is first installed. printer. This prints the page view and not the source code.
They may be customised to different arrangements. If this
has been done some of the following may be difficult to Working with text
follow.
Text typed directly onto the KompoZer page defaults to
To restore defaults click View > Show/Hide > Customize appearing in the format for the 'Body' element.
Toolbar > Main Toolbar > Restore Default Set and
repeat similarly for the Format Toolbar. Using KompoZer HTML defines a small number of elements specifically for
right-click any toolbar to customise it. text and it is usually preferable to use these. To format text
in a standard element format select the text and click the
Options for starting a page first drop-down box on the format toolbar. This offers a
selection of standard text formats. Paragraph is the most
There are several ways to start new pages or open existing appropriate for general text.
ones.
Once formatted as a paragraph, when typing in a text area,
To start a new blank page, on the menu bar click File > use of the 'enter' key starts a new block of text i.e. a
New. A window headed 'Create a new document or template' paragraph. To start a new line within the current paragraph
appears. Check the boxes 'A blank document' and 'Strict press Shift+Enter; this generates a line break.
DTD' and clear 'create a XHTML document'.

62 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B

Copyright Free under CC BY Licence


Other standard text formats are Heading formats from Tabs will be rendered as three non-breaking spaces. The
Heading 1, the largest (for the main heading), to Heading contents of tables may be pasted, individual cells will be
6, the smallest (for the least significant). Browsers separated as if by tabs.
generally render headings in bold type. Text can be edited
in any of the viewing modes and KompoZer responds to all Special characters
the normal windows shortcut commands.
By special characters we refer to characters which do not
Formatting text have an equivalent keyboard key. HTML uses a system of
characters known as 'Unicode'. This includes a large range
Text can be formatted in a number of ways using a format of characters including all the international currency symbols
toolbar. The changes listed in the table can be applied and many thousands of others, though the fonts supplied
(hover over a tool to discover what it does). on computers will support only a subset. A number of the
more common, including accented ones, may be inserted
Choose a font , Choose text colour, Choose using Insert > Characters and Symbols.
background colour, Choose highlight colour,
Make text smaller, Make text larger, Checking spelling
Embolden, Italicise, Underline, Format as a
numbered list, Format as a bulleted list, Align In any view, other than Source, click on the 'Spell' button.
left, Align Centre, Align right, Justify, Indent
text, Outdent text,Emphasise, Strongly .The spell checker will work sequentially through the
emphasise.
page.
Numbered and Bulleted lists
To insert an image
KompoZer can format a list of items giving each item a
1 Click the 'Image' button on the Composition toolbar
sequential number in any of several formats or presenting
them bulleted. To start a list from scratch 2 The Image properties window opens. Click 'Choose File'
and browse and select a file
1 Click one of the list buttons (Numbered List or Bulleted
3 Click 'Open'. Leave checked the box 'URL is relative to
list) on the Format toolbar.
page location' this will allow you to move the page and
2 Type the first item. image to another location, as you will have to when you
upload them to a server. (If you de-select this and move
3 Press Enter and type the next item.
the page, it will try to find the image at the original
4 To finish, on the last(blank) item press Enter. location.) Note If the box is 'greyed out' this is probably
because the page has not been saved.
To change existing text into a list
4 In the box labelled 'Alternate text' add a description of
1 Select the text required. the image. (This forms the 'alt' attribute for the image
2 Click one of the list buttons on the Format Toolbar. The and provides text which will appear in place of the image
text will be changed into a list, a new item starting for with user agents (browsers) that cannot display images
each paragraph or other block item encountered. (screen readers and voice synthesisers). It will also be
used by those with visual impairment. The content of
To add items to a list this box must be carefully considered so as to be of
maximum assistance in such cases.) Note Where the
1 Click at the end of the last item in the list. image is purely decorative, and not necessary to
2 Press Enter and type the new item. Numbering and understanding the page, alternative text is not required
format will continue from the previous item. and should be omitted
5 In the box labelled 'Tooltip' you may optionally insert a
Importing text 'Title' attribute for the image. Some browsers will show
Strictly KompoZer does not support importing text from the text provided when the cursor hovers over the image
other applications but it is possible to copy and paste text. 6 Click OK
In normal view content from other web pages may be copied
reliably. The result will be rendered according to any styling Using tables
applied in your document; any reliance on external styles
in the original document will be lost. Tables allow data - images, links, forms, form fields, text,
Text from word processors such as Microsoft Word or etc. - to be arranged into rows and columns of cells.
OpenOffice.org in rtf or doc format or from text editors such Inserting tables
as Windows notepad may also be copied and pasted.
When such text is pasted into KompoZer most formatting 1 On the Composition Toolbar click the Table button. The
is lost. Numbered lists will be retained. 'Insert table' window appears

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B 63

Copyright Free under CC BY Licence


2 Leave the 'Quickly' tab selected and drag out a matrix Inserting named Anchors
then click the bottom right cell to define the table
arrangement There is a second type of Anchor element the 'Named
anchor'. Such an anchor is extremely useful as it can act
3 The cells appear on the screen with narrow outlines
as a type of bookmark defining a particular place on a page.
Links can jump to such bookmarks.
Note: If later the table border is set to zero these
outlines disappear but KompoZer in normal
To insert a named anchor
view replaces them with a red outline. This
does not appear in Preview or in a browser.
1 Place the cursor at the point you want to mark.
Tables have resizing boxes similar to those
used with images 2 Click the 'Anchor' button on the Composition toolbar or,
on the Menu Bar, select Insert > Named Anchor. The
Table cell properties named anchor properties window appears.
3 Enter a unique name for the anchor.
Right-click the table and select 'Table Cell properties'. The
Table properties window opens. This has two tabs 'Table' 4 Click OK. In 'Normal' view anchors are marked by a
and 'Cells' which allow overall control of several aspects of picture of an anchor .
either the table or individual cells. This includes
Linking to named anchors
a Alignment of text within cells
b Wrapping of text Start as above for linking to another file. When the 'Link
Properties' window opens, instead of choosing file use the
c Cell spacing - the gap between cells
drop down list. Your anchor name should appear there
d Cell padding - the gap between the edge of the cell and preceded by a "#". Click it and OK. That's it! If you test your
the text within it page on a browser when you click the link the view should
move to show the position of the anchor.
e Size of table and cells
f Background colour Linking images
g Selection of cells as 'Normal' or 'Header' (Cells which
The techniques and possibilities are very similar to those
are headings to rows or columns should be selected as
used with text.
'Header'. Normally this results in them being rendered
in bold type.) To create a link
Linking text 1 Click on the image
2 On the Composition toolbar click on the 'Link' button,
Linking to another file
alternatively Right-click and select 'Create Link'. The
'Image Properties' window opens
To create a link
3 Click on 'Choose File' and browse to the file that you
1 Select (highlight) a few words of text want to link to. (The box 'URL is relative to page location'
is checked. This means that if you move your page to
2 On the Composition toolbar click on the 'Link' button,
a new folder you should move the image to a
alternatively Right-click and select 'Create Link'. The
corresponding new folder. If you clear this box the
'Link Properties' window opens
absolute address of the image on the hard drive is given
3 Click on 'Choose File' and browse to the file that you in full. If you move your page now it will look there for the
want to link to image. As you start to organise a web site you will find
4 Click OPEN that this is not a good arrangement and potentially
disastrous when you upload the page to a server.)
5 Click OK
4 Click OPEN
Inserting an email address
5 Click OK
Instead of linking to a file it is possible to insert an email
address. The result will be that, in use, when the link is Editing Links
clicked the email client on the visitor's machine will be
To change the file to which a link refers, in Normal, Tags or
opened with the correct address selected.
Preview mode double-click on the link. The 'Link properties'
To do so proceed as under the previous heading. When the window opens (for an image the 'Image Properties' window
Link Properties window opens (or if Image Properties click opens - click the Link tab). Edit the link.
the Link tab) enter the email address and check the box
To remove the link delete the link reference in the box.
'The above is an email address'.

64 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B

Copyright Free under CC BY Licence


Frames e.g. against level 1 select h3 and against level 2 select
h4 and for all the others select '--'
If you open a frame document, you get a message 'This
5 If, instead of using headings you wish to use classed
page can't be edited for an unknown reason' but it displays
paragraphs or a div, instead of selecting a heading tag
the frame content rather beautifully. Then you can do
select 'p' or 'div' and in the box in the column headed
nothing with it except click on the 'Source' tab. You then
'Class' enter the class required. (It is, of course, also
see the source code and the system will seem to lock up.
possible to select headings by allocating a class.)
Actually it doesn't lock and you can load another page and
revert to normal operation. 6 If you wish the contents to be numbered check the box
'Number all entries ...'
This is not a great limitation. Though the code for frames
7 Click OK
takes a little getting used to it is usually quite short and can
easily be produced using a text editor. Once established
The Table of Contents will be created.
it probably rarely needs to be altered. You can use
KompoZer to develop the pages that go into the frames. To update a ToC
Forms
After changes have been made to a page. There is no need
to place the cursor.
To set up a form
1 Click Insert > Table of Contents > Update
1 Click the form button.
2 The 'Table of Contents' window appears showing the
2 In the Form properties window give the form a name of
selections previously made
your choosing
3 If desired, changes may be made to the selections
3 Complete the Action box with the correct URL and
select the appropriate method 4 To update the ToC click OK
4 'Encoding' and 'Target Frame' will frequently not be To delete a ToC
required but, if they are, select 'More Properties' and
complete the boxes There is no need to place the cursor.
5 Click OK
1 Click Insert > Table of Contents > Remove
6 On the form place any headings, paragraphs and
images ensuring that there is a placeholder for any Style and stylesheets
controls needed. (If blank placeholders are needed it is
probably sensible to put some dummy text in now and Styles specify how particular elements on a page appear
delete it later.) on the screen, in print or whatever. Style may typically
7 Where controls are needed click the corresponding define aspects of presentation as the font face, size and
placeholder and using the drop down box beside the variant, the font colour, the background colour, whether an
Form button select the required control element is to be aligned right, centre or left, whether
spaced away from other elements, surrounded by a border
8 Give each control a unique name and, if so, what type or colour. Elements may be given an
9 Each control has specific information which needs to be absolute position relative to the page (which allows elements
entered. Enter it into the box in the window which to overlap).
appears Elements such as paragraphs, tables and images are
Table of contents considered to exist within boxes or blocks and the sizes of
these boxes may be specified.
If you have a long document with sections headed using
heading formats Heading 1, Heading 2 etcKompoZer can Classes As well as allowing you to specify the style of
generate a Table of Contents (ToC) automatically. The elements it is possible to define styles and apply them
table reflects the structure of the page, the content of the selectively to only some elements. This is done through
headings forming the text of the table. 'Classes' - a 'Class' is just a style that can be applied as and
when you choose. 'Classes' are applied to 'Tags' (a marker
Inserting a Table of Contents attached to an element). The element to which the class is
applied appears in the format defined by the class. Other
1 Place the cursor where the table is required similar elements without the class applied appear in the
default format i.e. either the default specified by the
2 Click Insert > Table of Contents > Insert
browser or the style that the user has defined for the
3 The 'Table of Contents' window appears corresponding element. On the status bar KompoZer
shows classes along with the tag to which they are applied.
4 In the column headed 'Tag' select the tag for each level
Fig 2 shows Style Nomenclature.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B 65

Copyright Free under CC BY Licence


Fig 2 6 You are now presented with a window headed'Selector'
followed by the tag for the element. The window actually
lists the style declarations for that element, but of
course that is now blank.

To define how you want elements to look

1 Select in turn as required the tabs for 'Text', 'Background',


'Border' etc and specify exactly how you wish that
element to appear. The next section amplifies some
details of how to do this.
2 Return to the general tab to see the full declarations that
you have set for the Selector.
3 If you click the 'General' tab you will see all the
Creating styles declarations for the rule. You can edit these here but it
is better to leave the job to CaScadeS because if you
Internal styles: AsKompoZer includes a CSS editor make any errors the declaration will be deleted
called CaScadeS which allows you to create stylesheets 4 When you are satisfied click 'OK'.
and define rules. Before you define a rule you must have a
stylesheet but if you are working on a page which has none Link to an existing stylesheet
CaScadeS will create one for you.
If you have a stylesheet that you created for another page
Creating a style rule for an element. or intend to use right across your site you can link your
page to that.
Css Stylesheet window (Fig 3)
To link to an existing external style sheet
Fig 3
1 Click the CaScadeS button on the Composition toolbar.
The CSS Stylesheets window opens
2 Click the dropdown arrow beside the artist's palette
button and select 'Linked stylesheet'
3 Click 'Choose file' and browse to the file that you need
4 Click 'Open'
5 Click 'Create stylesheet'
6 Click 'OK' You can now close CaScadeS, but, of course
you can work on the stylesheet in the usual way.

Saving stylesheets

Once you edit a stylesheet in KompoZer its name is


To create a style rule for an element marked by a red symbol indicating that it has not been
saved. When you close CaScadeS changed sheets are
1 Click the CaScadeS button on the Composition toolbar. saved immediately.
The CSS Stylesheets window opens.
2 Click on the artist's palette button. In the 'Sheets and Removing styles
rules' pane you will see an internal stylesheet has been CaScadeS allows you to remove styles in a similar way to
created for you. adding them. In the 'Sheets and rules' pane select the rule
3 To create a rule click 'Style applied to all elements of you want to remove and click 'Remove'. Similarly you can
type' remove a stylesheet. Select the sheet and click 'Remove'.
If you select an internal stylesheet it is deleted from the file
4 Beside the blank box click the drop down arrow. You will completely.
see listed a number of common elements. To create a
style for one of these click it alternatively enter the tag Templates
for any other element.
Templates are basically pages having some content (e.g.
5 Click 'Create Style rule' a letter head) which can be re-used to create other pages
which will have the same underlying page structure and,
often, the same graphical layout.

66 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B

Copyright Free under CC BY Licence


Templates are not altered in use and can be used over and To create a page using Template
over again. The simplest template is probably a blank sheet
which links to a stylesheet for use throughout a site. More 1 Click File > New > A new document based on a
common is a page which has a banner and perhaps a menu template > Choose File.
to appear on every page. Last might be a complete page 2 Select the Template (Note templates have the file
layout for use on all, or many, pages of a site but which extension 'mzt')
includes areas for customising individually. Templates
may be considered as having two parts - the fixed part or 3 Click 'Create'.
'boilerplate' which remains the same for every page and the
'editable part' which changes. To use the page

Create a template from a page 1 Click in turn in each editable areas.


2 Select and delete the sample text and replace it with
A pre-existing document may be transformed into a template new text.
1 Click Format > Page Title and Properties 2a If the editable area was repeatable a small square
appears within the label, hovering turns it red and
2 Check the box 'This page is a template'. clicking makes a copy. Copies have small circles
3 Click OK. which act as delete buttons.
4 Click File > Save as. The file type 'HTML Template' will 2b If any area was optional a small circle with an x
be completed. appears within the label. Hovering turns it red and
clicking deletes it. The same figure shows this for
5 Name and save the file as normal
the 'Other languages'. Because of the limitation
described it has not been possible to fill in all the
To save a template
editable areas.
1 Click File > Save or File > Save As. 3 When all editable boxes have been completed detach
the page from the template by clicking Edit > Detach
2 The extension 'mzt' will be selected automatically.
from template. The page now assumes its final
To make blocks editable appearance.
4 Save the page in the normal way. The last figure shows
1 In turn, select each block that you wish to make the final result. The areas which could not be edited
editable. earlier have been completed. Now it is possible to edit
2 In HTML tags view select the block by clicking its tag. any item and as a workaround the frozen repeatable
items may be added.
3 On the status bar right-click the corresponding
highlighted tag. Editing templates
4 Click Templates > Make editable. Templates which have already been saved may be altered
5 In the 'Insert an editable area' window give the block a after opening using menu commands File > Open File and
recognisable name. Now check the options boxes if selecting 'Files of Type' then 'HTML Templates'.
required.
Site Manager
6 Click OK.
The site manager allows you to navigate your site or
To make a flow selection editable between sites easily. To toggle the Site Manager on or off
either press F9 or use View > Show/Hide > Site Manager.
1 In turn select (highlight) each section of text that you Site Manager can deal with sites irrespective of whether
wish to make editable. they reside on a local machine or on a remote server. In the
2 Click Insert > Templates >Insert editable area. latter case, if you are on a dial-up network, Site Manager
will dial and make the connection for you. Since generally
3 In the 'Insert an editable area' window give the block a you will set up a site on a local machine and later 'publish'
recognisable name. to a remote server we will deal first with setting up on a local
4 Leave checked the option 'Flow of text'. machine. Site Manager provides a directory tree view of a
site similar to the view with Windows Explorer. It however
5 Check the options boxes if required as described lists only directories which you have specifically set up as
above. Note The option 'Area is moveable' is inappropriate 'Sites'. You can set up many sites, they appear in Site
for flow areas). Manager irrespective of where they appear in a normal
6 Click OK directory tree.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B 67

Copyright Free under CC BY Licence


Setting Preferences • HTTP address (URL) of your site. From your ISP (see
hints).
You can set up a number of features in KompoZer according
• Publishing address - This is the ftp address to which
to personal preferences. Several of the options are grouped
you will publish.
under the Tools >Optons menu. In addition you can
customise toolbars via the View > Show/hide menu. • User name - From your ISP.
• Password - From your ISP.
Defaults
• If you wish to, check 'Save Password'. If you have
The defaults set by KompoZer will generally be found several sites set up and you have one site that you
satisfactory. (Fig 4) always or usually publish to you may wish to click on
the name of this site then 'Set as default'. This simplifies
Fig 4
uploading. Click OK.

Uploading

Open the page that you want to upload. An easy way to do


this is from the Site Manager.

1 Click the 'Publish' button.


2 On the 'Publish Page' window on the 'Publish' tab, if it
is not your default, in the 'Site name' box select the site
to which you want to publish. The 'Page title' and 'File
name' should already be completed.
3 If the page is to be uploaded to a sub-directory, rather
than the root directory, enter the name of a sub-
directory and any of the other data if required.

Note: This directory must exist. KompoZer


cannot create it.

4 If it is the first time to upload the page, and if it includes


Editing preferencesKompoZer can be customised in several images or uses external style sheets, check the box
ways through the Menu selection Tools > Options 'Include images and other files'. (If it is not the first time
mechanism. All the options may be set at any time. All and these other files have not changed the box may be
take effect immediately except for 'New page settings' left unchecked.) The files will be placed in the same
which do not apply to any existing page. directory as the page. If you want them to go in a sub-
directory check the box 'Use this site sub-directory' and
Publishing name the directory. In this case the directory will be
created if needed.
Introduction Publishing a site means transferring the site,
5 You should not need to refer to the 'Settings' tab as the
i.e. the pages, images and stylesheets involved, to a web
data should be collected via the Site name you have
server from which they may be accessed, usually but not
selected but you may view the data and change if you
necessarily, by the public. This process is called 'Uploading'.
wish.
Prior to publishing there are a few checks which should be
carried out. 6 Click 'Publish'. A 'Publishing' window will appear and
uploading will commence. (If you are on a dial-up
Setting up your site connection this will be connected.)
7 Within a short time you should receive confirmation of
While setting up Site Manager you may already have
correct publication similar to the first figure above.
configured the 'remote' site, if not, either proceed as
detailed there, go directly to Publish Settings via Edit > 8 One possible source of problems occurs if you are
Publishing Site settings. prevented from accessing the site by a firewall. In this
case you may receive a 'Publishing failed' message
Confirmation of correct publication Enter the following similar to that shown in the second figure.
details:
The 'Troubleshooting' button takes you to the KompoZer
• In the 'Site names' box enter the name that you want to help system but this is short of aid in this area at present.
know the site by.

68 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B

Copyright Free under CC BY Licence


Other possible problems include Fig 6

• Some required files are missing


• File or directory names incorrect e.g. Wrong case

Once you have published a page, if you need to publish it


again, your settings (e.g. subdirectories) should be
remembered by KompoZer. You will not see steps 2 to 4
again unless changes have been made to the page. Fig 5
and Fig 6 shows publishing window.
Fig 5

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B 69

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.102C
COPA - JavaScript and creating Web page

Concepts of Animation and Multimedia files in JavaScript


Objectives : At the end of this lesson you shall be able to
• know animation settings in JavaScript
• explain multimedia in JavaScript.

Animation The Animation Code

Styling the Elements JavaScript animations are done by programming gradual


changes in an element's style. The changes are called by
To make an animation possible, the animated element a timer. When the timer interval is small, the animation
must be animated relative to a "parent container". looks continuous. The basic code is:

The container element should be created with style = Example


"position: relative".
var id = setInterval(frame, 5);
The animation element should be created with style =
function frame() {
"position: absolute".
if (/* test for finished */) {
Example
clearInterval(id);
<!Doctype html> } else {
<html> /* code to change the element style */
<style> }
#myContainer { }
width: 400px;
Create the Animation Using JavaScript
height: 400px;
Example
position: relative;
background: pink; <style>`
} #myContainer {
#myAnimation { width: 400px;
width: 50px; height: 400px;
height: 50px; position: relative;
position: absolute; background: pink;
background: green; }
} #myAnimation {
</style> width: 50px;
<body> height: 50px;
<h1>My First JavaScript Animation</h1> position: absolute;
<div id="myContainer"> background-color: green;
<div id="myAnimation"></div> }
</div> </style>
</body> <body>
</html> <p>
? <button onclick="myMove()">Click Me</button>
</p>

70

Copyright Free under CC BY Licence


<div id ="myContainer"> How it Works
<div id ="myAnimation"></div>
The controls attribute adds video controls, like play, pause,
</div> and volume. It is a good idea to always include width and
height attributes. If height and width are not set, the page
<script>
might flicker while the video loads. The <source> element
function myMove() { allows you to specify alternative video files which the
var elem = document.getElementById("myAnimation"); browser may choose from. The browser will use the first
recognized format. The text between the <video> and </
var pos = 0; video> tags will only be displayed in browsers that do not
var id = setInterval(frame, 10); support the <video> element.

function frame() { HTML <video> Autoplay


if (pos == 350) {
To start a video automatically use the autoplay attribute:
clearInterval(id);
} else { Example

pos++; <video width="320" height="240" autoplay>


elem.style.top = pos + 'px'; <source src="movie.mp4" type="video/mp4">
elem.style.left = pos + 'px'; <source src="movie.ogg" type="video/ogg">
} Your browser does not support the video tag.
} </video>
}
Note: Autoplay attribute does not work in mobile
</script> devices like iPad and iPhone
</body>
HTML Video - Media Types
</html>
File Format Media Type
Multimedia files
MP4 video/mp4
What is Multimedia?
WebM video/webm
Multimedia comes in many different formats. It can be
Ogg video/ogg
almost anything you can hear or see. Web pages often
contain multimedia elements of different types and formats.
HTML Video - Methods, Properties, and Events
Examples: Images, music, sound, videos, records, films,
animations and more. HTML5 defines DOM methods, properties, and events for
the <video> element. This allows you to load, play, and
Multimedia Formats pause videos, as well as setting duration and volume. There
are also DOM events that can notify you when a video
Multimedia elements (like audio or video) are stored in begins to play, is paused, etc.
media files. The most common way to discover the type of
a file, is to look at the file extension. Multimedia files have HTML5 Video Tags
formats and different extensions like: .swf, .wav, .mp3,
.mp4, .mpg, .wmv, and .avi. Tag Description

Playing Videos in HTML <video> Defines a video or movie


To show a video in HTML, use the <video> element: <source> Defines multiple media resources for
media elements, such as <video> and
Example <audio>
<video width="320" height="240" controls>
<track> Defines text tracks in media
<source src="movie.mp4" type="video/mp4"> players
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102C 71

Copyright Free under CC BY Licence


Audio on the Web HTML Audio - Media Types

The HTML5 <audio> element specifies a standard way to File Format Media Type
embed audio in a web page.
MP3 audio/mpeg
The HTML <audio> Element
OGG audio/ogg
To play an audio file in HTML, use the <audio> element:
WAV audio/wav
Example
HTML Audio - Methods, Properties, and Events
<audio controls>
HTML5 defines DOM methods, properties, and events for
<source src="horse.ogg" type="audio/ogg"> the <audio> element. This allows you to load, play, and
<source src="horse.mp3" type="audio/mpeg"> pause audios, as well as set duration and volume. There
are also DOM events that can notify you when an audio
Your browser does not support the audio element. begins to play, is paused, etc.
</audio>
HTML5 Audio Tags
HTML Audio - How It Works
Tag Description
The controls attribute adds audio controls, like play,
pause, and volume. The <source> element allows you to <audio> Defines sound content
specify alternative audio files which the browser may
choose from. The browser will use the first recognized <source> Defines multiple media resources
format. The text between the <audio> and </audio> tags for media elements, such as
will only be displayed in browsers that do not support the <video> and <audio>
<audio> element.

72 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102C

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.1.103A & 2.1.103B
COPA - JavaScript and creating Web page

Introduction to IIS and XAMPP, Dynamic Website and Hosting and FTP tool
Filezilla - Projects in JavaScript
Objectives : At the end of this lesson you shall be able to
• describe XAMPP
• describe what is included in XAMPP
• describe FTP
• describe fileZilla
• describe a web project
• follow SDLC.

Introduction Different versions of XAMPP may have additional


components such as phpMyAdmin, OpenSSL, etc. to
XAMPP is a free and open source cross-platform web server create full-fledged web servers.
solution stack package, consisting mainly of the Apache
HTTP Server, MySQL database, and interpreters for scripts XAMPP features
written in the PHP and Perl programming languages.
XAMPP requires only one zip, tar, or exe file to be
XAMPP's name is an acronym for: downloaded and run, and little or no configuration of the
various components that make up the web server is
• X (to be read as "cross", meaning cross-platform) required. XAMPP is regularly updated to incorporate the
• Apache HTTP Server latest releases of Apache, MySQL, PHP and Perl. It also
comes with a number of other modules including OpenSSL
• MySQL and phpMyAdmin.
• PHP
Self-contained, multiple instances of XAMPP can exist
• Perl on a single computer, and any given instance can be copied
What's Included in XAMPP? from one computer to another.

XAMPP has four primary components. These are: It is offered in both a full, standard version and a smaller
version.
1 Apache: Apache is the actual web server application
that processes and delivers web content to a computer. Use
Apache is the most popular web server online, powering
nearly 54% of all websites. Officially, XAMPP's designers intended it for use only as a
2 MySQL: Every web application, howsoever simple or development tool, to allow website designers and
complicated, requires a database for storing collected programmers to test their work on their own computers
data. MySQL, which is open source, is the world's most without any access to the Internet. To make this as easy
popular database management system. It powers as possible, many important security features are disabled
everything from hobbyist websites to professional by default. In practice, however, XAMPP is sometimes
platforms like WordPress. You can learn how to master used to actually serve web pages on the World Wide Web.
PHP with this free MySQL database for beginners A special tool is provided to password-protect the most
course. important parts of the package.

3 PHP: PHP stands for Hypertext Preprocessor. It is a XAMPP also provides support for creating and manipulating
server-side scripting language that powers some of the databases in MySQL and SQLite among others.
most popular websites in the world, including
WordPress and Facebook. It is open source, relatively Once XAMPP is installed, it is possible to treat a localhost
easy to learn, and works perfectly with MySQL, making like a remote host by connecting using an FTP client.
it a popular choice for web developers. Using a program like FileZilla has many advantages when
installing a content management system (CMS) like
4 Perl: Perl is a high-level, dynamic programming
Joomla or WordPress. It is also possible to connect to
language used extensively in network programming,
localhost via FTP with an HTML editor.
system admin, etc. Although less popular for web
development purposes, Perl has a lot of niche
The default FTP user is "newuser", the default FTP
applications.
password is "wampp". The default MySQL user is "root"
while there is no default MySQL password.

73

Copyright Free under CC BY Licence


XAMPP 1.8.3-4 for Windows, includes the current specification. Several proposed standards
amend RFC 959, for example RFC 2228 (June 1997)
• Apache 2.4.9 proposes security extensions and RFC 2428 (September
• MySQL 5.6.16 1998) adds support for IPv6 and defines a new type of
passive mode.
• PHP 5.5.11
Login
• phpMyAdmin 4.1.12
• FileZilla FTP Server 0.9.41 FTP login utilizes a normal username and password
• Tomcat 7.0.42 (with mod_proxy_ajp as connector) scheme for granting access. The username is sent to the
server using the USER command, and the password is
• Strawberry Perl 5.16.3.1 Portable sent using the PASS command. If the information provided
• XAMPP Control Panel 3.2.1 (from hackattack142) by the client is accepted by the server, the server will
send a greeting to the client and the session will
XAMPP 1.8.3-4 for Linux, includes commence. If the server supports it, users may log in
without providing login credentials, but the same server
• Apache 2.4.9 may authorize only limited access for such sessions.

• MySQL 5.6.16 Anonymous FTP


• PHP 5.5.11
A host that provides an FTP service may provide
• phpMyAdmin 4.1.12 anonymous FTP access. Users typically log into the
• OpenSSL 1.0.1g service with an 'anonymous' (lower-case and case-sensitive
in some FTP servers) account when prompted for user
XAMPP is also available for Mac OS. name. Although users are commonly asked to send their
email address instead of a password, no verification is
File Transfer Protocol actually performed on the supplied data. Many FTP hosts
whose purpose is to provide software updates will allow
The File Transfer Protocol (FTP) is a standard network anonymous logins.
protocol used to transfer computer files from one host to
another host over a TCP-based network, such as the NAT and firewall traversal
Internet.
FTP normally transfers data by having the server connect
FTP is built on a client-server architecture and uses back to the client, after the PORT command is sent by
separate control and data connections between the client the client. This is problematic for both NATs and firewalls,
and the server. FTP users may authenticate themselves which do not allow connections from the Internet towards
using sign-in protocol, normally in the form of a username internal hosts. For NATs, an additional complication is
and password, but can connect anonymously if the server that the representation of the IP addresses and port number
is configured to allow it. For secure transmission that in the PORT command refer to the internal host's IP
protects the username and password, and encrypts the address and port, rather than the public IP address and
content, FTP is often secured with SSL/TLS (FTPS). SSH port of the NAT.
File Transfer Protocol (SFTP) is sometimes also used
instead, but is technologically different. There are two approaches to this problem. One is that the
FTP client and FTP server use the PASV command, which
The first FTP client applications were command-line causes the data connection to be established from the
applications developed before operating systems had FTP client to the server. This is widely used by modern
graphical user interfaces, and are still shipped with most FTP clients. Another approach is for the NAT to alter the
Windows, Unix, and Linux operating systems. Many FTP values of the PORT command, using an application-level
clients and automation utilities have since been developed gatewayfor this purpose.
for desktops, servers, mobile devices, and hardware, and
FTP has been incorporated into productivity applications, Differences from HTTP
such as Web page editors.
When operating in its modern passive mode, FTP uses a
History of FTP server single socket for both signalling and for actual file data,
just like the HTTP protocol. But when used in its original
The original specification for the File Transfer Protocol was configuration, in "active mode" with a separate socket for
written by Abhay Bhushan and published as RFC 114 on the download, FTP exhibits true out-of-band control which
16 April 1971. Until 1980, FTP ran on NCP, the predecessor is not an option with HTTP.
of TCP/IP. The protocol was later replaced by a TCP/IP
version, RFC 765 (June 1980) and RFC 959 (October 1985),

74 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.103A & 2.1.103B

Copyright Free under CC BY Licence


Web browser support Secure FTP

Most common web browsers can retrieve files hosted on Securing FTP transfers may be accomplished by several
FTP servers, although they may not support protocol methods.
extensions such as FTPS. When an FTP-rather than an
HTTP-URL is supplied, the accessible contents on the FTPS
remote server are presented in a manner that is similar to
that used for other Web content. A full-featured FTP client Explicit FTPS is an extension to the FTP standard that
can be run within Firefox in the form of an extension called allows clients to request that the FTP session be
FireFTP. encrypted. This is done by sending the "AUTH TLS"
command. The server has the option of allowing or denying
Syntax connections that do not request TLS. This protocol
extension is defined in the proposed standard: RFC 4217.
FTP URL syntax is described in RFC1738, taking the form: Implicit FTPS is a deprecated standard for FTP that required
ftp://[<user>[:<password>]@]<host>[:<port>]/<url-path> the use of a SSL or TLS connection. It was specified to
The bracketed parts are optional. use different ports than plain FTP.

For example, the URL ftp://public.ftp-servers.example.com/ SFTP


mydirectory/myfile.txt represents the file myfile.txt from
the directory mydirectory on the server public.ftp- The SSH file transfer protocol or secure FTP (SFTP), also
servers.example.com as an FTP resource. The URL ftp:// transfers files and has a similar command set for users,
user001:[email protected] but is built on different software technology. SFTP uses
servers.example.com/mydirectory/myfile.txt adds a theSecure Shell protocol (SSH) to transfer files. Unlike
specification of the username and password that must be FTP, it encrypts both commands and data, preventing
used to access this resource. passwords and sensitive information from being transmitted
openly over the network. It cannot interoperate with FTP
More details on specifying a username and password may software.
be found in the browsers' documentation, such as, for
example, Firefox and Internet Explorer. By default, most FTP over SSH (not SFTP)
web browsers use passive (PASV) mode, which more
easily traverses end-user firewalls. FTP over SSH is the practice of tunneling a normal FTP
session over a Secure Shell connection. Because FTP
Security uses multiple TCP connections (unusual for a TCP/IP
protocol that is still in use), it is particularly difficult to
FTP was not designed to be a secure protocol, and has tunnel over SSH. With many SSH clients, attempting to
many security weaknesses. In May 1999, the authors of set up a tunnel for the control channel (the initial client-to-
RFC 2577 listed a vulnerability to the following problems: server connection on port 21) will protect only that channel;
when data is transferred, the FTP software at either end
• Brute force attacks sets up new TCP connections (data channels) and thus
• Bounce attacks have no confidentiality or integrity protection.

• Packet capture (sniffing) Otherwise, it is necessary for the SSH client software to
have specific knowledge of the FTP protocol, to monitor
• Port stealing
and rewrite FTP control channel messages and
• Spoof attacks autonomously open new packet forwardings for FTP data
• Username protection channels. Software packages that support this mode
include:
FTP does not encrypt its traffic; all transmissions are in
clear text, and usernames, passwords, commands and • Tectia ConnectSecure (Win/Linux/Unix) of SSH
data can be read by anyone able to perform packet capture Communications Security's software suite
(sniffing) on the network. This problem is common to many • Tectia Server for IBM z/OS of SSH Communications
of the Internet Protocol specifications (such as SMTP, Security's software suite
Telnet, POP and IMAP) that were designed prior to the
creation of encryption mechanisms such as TLS or SSL. • FONC (the GPL licensed)
A common solution to this problem is to use the "secure", • Co:Z FTPSSH Proxy
TLS-protected versions of the insecure protocols (e.g.
FTPSfor FTP, TelnetS for Telnet, etc.) or a different, more Other methods of transferring files using SSH that are not
secure protocol that can handle the job, such as the SFTP/ related to FTP include SFTP and SCP; in each of these,
SCP tools included with most implementations of the the entire conversation (credentials and data) is always
Secure Shellprotocol. protected by the SSH protocol.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.103A & 2.1.103B 75

Copyright Free under CC BY Licence


FILEZILLA The SDLC adheres to important phases that are essential
for developers, such as planning, analysis, design, and
FileZilla is a free FTP solution. Both a client and a server implementation, and are explained in the section below. It
are available. FileZilla is open source software distributed includes evaluation of present system, information
free of charge under the terms of the GNU General Public gathering, feasibility study and request approval. A number
License. Using FileZilla files can be uploaded or of SDLC models have been created: waterfall, fountain,
downloaded from client to server and vice-versa. It is very spiral, build and fix, rapid prototyping, incremental, and
user friendly and no commands are required to do upload synchronize and stabilize. The oldest of these, and the
and download operations. Files can be uploaded or best known, is the waterfall model: a sequence of stages
downloaded by simple drag-drop operations. in which the output of each stage becomes the input for
the next. These stages can be characterized and divided
Designing a Web Project: A project in Web should be up in different ways, including the following:
developed after comprehensive enquiry about what exactly
the client/end user want. For this some meeting can be • Preliminary analysis: The objective of phase 1 is to
arranged with clients to find out the exact requirement of conduct a preliminary analysis, propose alternative
the client. This is called SRS(System Requirement solutions, describe costs and benefits and submit a
Specification). preliminary plan with recommendations.
Some methods are followed for SRS, which are giving some • Conduct the preliminary analysis: in this step, you
questions abount the system to the clients and verifying need to find out the organization's objectives and the
the answer to gauge the requirement of the clients. Showing nature and scope of the problem under study. Even if a
them some demo screen to get their response. Collecting problem refers only to a small segment of the
the reports they use to understand the type of data they organization itself then you need to find out what the
use. objectives of the organization itself are. Then you need
to see how the problem being studied fits in with them.
Before development of any system or project, SRS is very
• Propose alternative solutions: In digging into the
important as if you cannot understand the exact user
organization's objectives and specific problems, you
requirement, then the system/project developed by you
may have already covered some solutions. Alternate
with lot of man hours spent on it would be totally wasted
proposals may come from interviewing employees,
and the project would be scraped.
clients, suppliers, and/or consultants. You can also
SDLC: The systems development life cycle (SDLC), also study what competitors are doing. With this data, you
referred to as the application development life-cycle, is a will have three choices: leave the system as is, improve
term used in systems engineering, information systems it, or develop a new system.
and software engineering to describe a process for Describe the costs and benefits.
planning, creating, testing, and deploying an information
system. (Fig 1) • Systems analysis, requirements definition: Defines
project goals into defined functions and operation of
Fig 1 the intended application. Analyzes end-user information
needs.
• Systems design: Describes desired features and
operations in detail, including screen layouts, business
rules, process diagrams, pseudo code and other
documentation.
• Development: The real code is written here.
• Integration and testing: Brings all the pieces together
into a special testing environment, then checks for
errors, bugs and interoperability.
• Acceptance, installation, deployment: The final
stage of initial development, where the software is put
into production and runs actual business.
• Maintenance: During the maintenance stage of the
SDLC, the system is assessed to ensure it does not
become obsolete. This is also where changes are made
The system development life cycle framework provides a to initial software. It involves continuous evaluation of
sequence of activities for system designers and developers the system in terms of its performance.
to follow. It consists of a set of steps or phases in which
each phase of the SDLC uses the results of the previous
one.

76 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.103A & 2.1.103B

Copyright Free under CC BY Licence


• Evaluation: Some companies do not view this as an • Disposal: In this phase, plans are developed for
official stage of the SDLC, but is it an important part of discarding system information, hardware and software
the life cycle. Evaluation step is an extension of the in making the transition to a new system. The purpose
Maintenance stage, and may be referred to in some here is to properly move, archive, discard or destroy
circles as Post-implementation Review. This is where information, hardware and software that is being
the system that was developed, as well as the entire replaced, in a matter that prevents any possibility of
process, is evaluated. Some of the questions that need unauthorized disclosure of sensitive data. The disposal
to be answered include: does the newly implemented activities ensure proper migration to a new system.
system meet the initial business requirements and Particular emphasis is given to proper preservation and
objectives? Is the system reliable and fault-tolerant? archival of data processed by the previous system. All
Does the system function according to the approved of this should be done in accordance with the
functional requirements? In addition to evaluating the organization's security requirements.
software that was released, it is important to assess
In the following example (Fig 2) these stages of the
the effectiveness of the development process. If there
systems development life cycle are divided in ten steps
are any aspects of the entire process, or certain stages,
from definition to creation and modification of IT work
that management is not satisfied with, this is the time
to improve. Evaluation and assessment is a difficult products:
issue. However, the company must reflect on the
process and address weaknesses.

Fig 2

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.103A & 2.1.103B 77

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.104
COPA - Programming with VBA

Introduction to VBA features and applications


Objectives : At the end of this lesson you shall be able to
• describe the applications of VBA
• explain the terms objects and properties
• explain macros, procedures and events
• explain the debugging techniques in VBA.

Introduction to VBA • Creating invoices and other forms


• Developing charts from data
VBA is the acronym for Visual Basic for Applications. It is
an integration of Microsoft's event-driven programming
Using VBA results in the following advantages for
language Visual Basic with Microsoft Office applications.
the user:
This is the standard Macro language used in most Microsoft
Office products like Excel, Access etc. The VBA language
• Time Saving.
is a derivative of Visual Basic (VB). The fundamental
difference with VBA from VB is that VBA is used within an • Consistent results at much greater speed.
Application. By running VBA within the Microsoft Office • Customized tasks creation to make working easy for
applications, you can build customized solutions and the users.
programs to enhance the capabilities of those applications. s
There is built-in Visual Basic Editor in Microsoft Excel • Functionally rich and extremely flexible.
that can be used to customize and extend capabilities of • Simple to use and create applications
MS Excel. The applications built with MS Excel are called
Visual Basic for Applications, or simply VBA. Disadvantages of VBA

Common Uses of VBA As macros are the heart of VBA, there is always a threat
of macro viruses embedded in them. Unless proper steps
• Customizing and extending the functionality of the are taken to prevent this misuse, the application may be
Application in which it is used. targeted in a potentially unsafe manner.This can be tackled
by using proper antivirus products and verifying the
• Automating a task you perform frequently Ex. Monthly certificates of the embedded macros.
reports etc.
• Automating repetitive operations Ex. repeating a set of Common Terms used in Excel VBA
actions on many workbooks
Object oriented programming
• Creating a custom command for ex. one that combines
many commands to make the work faster The word Object is used to describe just about everything
• Creating user interactive forms and controls like buttons in Excel. In Excel, an Object can be Form, Button, Chart
to which macros or code can be assigned or even the Visual Basic Editor (VBE) itself.

• Customizing the Quick Access Toolbar with your own In object-oriented programming, a class is a code element
buttons that execute the macros you write. that defines an object. A good analogy for a class module
• Developing new worksheet functions that can greatly is the specification that defines a Window, Button or a
simplify your formulas. Sheet etc. You create an object using the class as its
specification. A Class is therefore a template from which
• Creating complete, macro-driven applications. objects are created. Objects can be treated as instances
• Creating custom add-ins for Excel of Classes. You add code to the class module to define
the object's properties and methods. Modifying the code
Some of the common applications of VBA are: in a class module modifies how the object defined by the
class module behaves.
• Keeping lists of things such as employees' details,
customers'records, students' grades etc. In the Object Hierarchy, at the top is the Application Object,
ie. Excel here. Next in this order is Workbook Object e.g.;
• Customized data entry with subsequent actions
Book1.xlsx. Directly underneath the Workbook Object
included
comes the Worksheet Object. At the Worksheet Object
• Budgeting and forecasting the Object Hierarchy branches off to incorporate all Objects
of the Worksheet. The first one you will most likely
• Data Analysis
encounter will be the Range Object. Branching from the

78

Copyright Free under CC BY Licence


Range Object there are again many other objects such as Methods
the Areas Object, the Borders Object, Font Object,
Characters, etc. In brief, the hierarchy is as follows: A Method is simply a procedure that acts on an Object. It
makes the Object do something, like opening a Workbook
• Application or deleting a Worksheet etc. Examples of some methods
of VBA objects are the Activate, Copy, Delete, Save
• Workbook
methods of the Worksheet, the Add Item and clear methods
• Worksheet of the combo Box and list box etc.
• Range
Events
When you have a group of Objects that are related, this is
then known as a "Collection". So when we use the term An Event in Excel VBA is the reason or trigger for an
Workbooks, we are referring to all open Workbooks, and action to take place. For example a mouse click is an
when we use the term Workbook, we are only referring to event, Double Clicking an object is an event, closing or
an individual Workbook (the active Workbook). opening of a Workbook are also events. The action to be
taken when the event occurs is written as code in the
Properties event procedure. Examples of events are the Click,
DoubleClick events of Buttons, Scroll, and Change Events
Properties are attributes of an Object. They are used to of the Scroll Bar etc.
define an Objects characteristics. For example; the
Worksheet Object has many Properties, one of which Modules
would be its name. By changing the Visible Property, we
may hide or unhide it. To be able to change the Property Modules are containers for holding VBA code. Modules
of any Object we must first identify the Object whose can contain declarations and procedures. VBA code that
Property we wish to change. Examples of properties are is placed in one or more modules can be called from an
height, width, font color, name etc. to name a few. Office application to perform a specified task.

Macros The following are the elements of the VBA Module

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.

Procedures Class modules are modules that are associated with a


particular object. Class modules can be used either for
Procedures are a named set of statements that are form or report modules or for custom objects accessible
executed as a whole. They tell Excel how to perform a throughout your VBA application. For example, form and
specific task. The task performed can be very simple or report modules can contain code that corresponds to a
very complicated. It is good practice to break long or particular form or report. An example of a form module is
complicated procedures into smaller sized logically an event procedure, such as the Click event for a control
ordered procedures. The two main types of Procedures on a form.
are Sub and Function. In VBA a Sub procedure either
results from recording a macro or results in the creation of One way to create a module is to select the Modules tab
a macro, while Function procedure must be written only in the database window and click the New button. Another
manually. All Sub procedures must begin with the word way to create a module is to select Insert → Module.
Sub followed by a chosen name and then a set of
parenthesis. All Subs must end with End Sub. The Visual Basic Editor

The Visual Basic Editor is where the actual programming


is done. There are many ways to access the VBA editor.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.104 79

Copyright Free under CC BY Licence


One among them is using the shortcut key Alt + F11. You Project Explorer and Properties Window
can also access the Visual Basic Editor from Tools >
Macro > Visual Basic Editor from the Excel Worksheet. To open the Project Explorer, go to View > Project
Explorer, or use the shortcut keys, Ctrl + R. To view the
At the very top of the VBE you have what is known as the Properties window, go to View> Properties Window,or
Menu Bar. From this one menu bar it is possible to access click F4. The Project explorer contains all the objects like
most functions of the VBE. If you right click on the grey sheets, Books, modules etc. If you now click on Sheet1
area just to the right of Help on the Menu Bar a shortcut in the Project Explorer you will see in the Properties
menu will appear. Select Customize... Here you will see Window a list of all the Properties for a
the names of all the Toolbars that can be available to you.
As a general default you will have the Menu Bar and the To the right side of the project explorer and properties
Standard Toolbar displayed. window is the code window where the actual programming
is done. (Fig 1)

Fig 1

Saving Excel files containing macros or VBA code. Debugging in VBA

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.

Debugging is used for fixing Bugs, analysis during


development and supporting deployed applications.

80 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.104

Copyright Free under CC BY Licence


Debugger Step Out [Ctrl Shift F8]

There are several parts of the debugger that work together Run the current procedure and go to the line after the line
to let you analyze how your code runs: that called the procedure. This is basically a way to simplify
the debugging process by letting you skip the remainder
• Integrated Development Environment (IDE) of the current procedure once you realize you don't need
to step into it any more.
• Breakpoints
• Stepping Through and Over Code Set Next Statement [Ctrl F9]
Integrated Development Environment (IDE)
This command lets you set the next statement as any
line in the current procedure including lines you've already
From the IDE, there are several things you can do:
run. It is particularly useful if you run though some code
Current Definition [Shift F2] and then decide you should repeat it because you missed
something.
Put the cursor on the variable, procedure, or property in
question and press [Shift F2] to see where it's defined. Show Next Statement
You'll jump directly to it. You can do this as often as you
like to understand how your code works. Press [Ctrl Shift Sometimes you examine different procedures as you debug
F2] to go back to where you came. your code, so the Show Next Statement menu command
makes it easy to go to the currently highlighted line.
Run the Current Procedure
Debugging Views
Highlight the procedure you want to run and press [F5] to
run it. If you want to step into it line-by-line, press [F8]. Of In addition to seeing which line of code runs and evaluating
course, running a procedure this way only works if you variables as you debug, there are several other views that
don't have to pass parameters to it. If you need to, consider help you diagnose your development environment:
using the Immediate Window.
• Call Stack
Breakpoints • Immediate Window

Breakpoints are placed on the lines in your code so the • Locals Window
debugger is invoked when the program tries to execute • Watch Window
that line. A breakpoint can be placed on any line that is
actually run (not lines in the General Declarations section, Call Stack [Ctrl L]
or lines that define variables in a procedure). This is an
extremely powerful technique to let you run your code The call stack keeps track of the procedure calling chain
normally until the section you're interested in is so you can easily see how you got to the current procedure
encountered. through all the other procedures. Retrieve it under View,
Call Stack, or press [Ctrl L].
Breakpoints can be added by moving to the line desired
and pressing F9, clicking with the mouse on the left border, From this dialog, you can click on any procedure and
or from the Debug menu. Multiple breakpoints can be jump immediately to it. Before analyzing the details of the
added during your debugging session. Breakpoints are current procedure, it may be more important to understand
temporary and are automatically removed when you close how and why you got there since the problem may be
the VBA. there rather than in the current procedure.

Stepping Through Code Immediate Window [Ctrl G]

The debugger gives you a variety of techniques to step This is the most basic debugging area. You can use the
through your code: Immediate Window whether your code is running or not.
Open the Immediate Window by pressing [Ctrl+G] or
Step Into [F8] selecting it from the IDE menu under View. The Immediate
window lets you:
Run the current line and go to the next one.
• Evaluate expressions unrelated to your code (e.g. math
Step Over [Shift F8] equations)
• Evaluate variables or expressions in your code (e.g. a
Used for a line that calls a procedure to run that procedure
current variable value)
without going into it. The command lets you run the
procedure (and any procedures it may call), and go to the • Run code
next line in the calling procedure.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.104 81

Copyright Free under CC BY Licence


For items that return a value, use a question mark followed Watch Window
by the expression. For instance:? 14/5 then click Enter to
see the value. If your code is currently running and stopped, The Watch Window is similar to the Locals Window, but
you can use this method to evaluate the current value of a you specify the variables you want to track. You can track
variable: ? pay variables across modules and procedures and keep them
in your Watch Window to see their value no matter where
Locals Window the current line is.

You can see all the local variables by selecting Locals The first step is to add a variable to the Watch Window.
Window from the Views menu. This displays the entire This can be done by placing the cursor in the variable you
list of local variables and their current values. Local variables want to track, and selecting Debug, Add Watch, or from
are variables defined in the current procedure and module the right-click menu, selecting Add Watch. The current
declaration section. variable is added to the Expression section, and the current
procedure and module added to the Context sections. You
You can modify the value held by a variable by clicking on can also add expressions, and options to break when the
the Value column and editing it. This is an alternative to value changes. This is particularly useful when you are
modifying values from the Immediate Window. having trouble determining why a particular situation arises
in your application.

82 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.104

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.105A - 2.2.105D
COPA - Programming with VBA

Form Controls and Properties in VBA


Objectives: At the end of this lesson you shall be able to
• differentiate form controls and activeX controls in VBA
• describe the types of form controls and activeX controls
• describe the properties, methods and events of controls.

Introduction ActiveX controls provide more flexibility in changing or


setting the properties both at design time and run time.
Controls are objects that display data or make it easier for Form controls allow you to assign predefined macros or
users to enter or edit data, perform an action, or make a subroutines to them but offer limited choices in modifying
selection. In general, controls make the form easier to the properties. In addition to these sets of controls, you
use. Examples of common controls include list boxes, can also add objects from the Drawing tools, such as
option buttons, and command buttons. Controls can also Auto Shapes, Word Art, Smart Art graphic, or text boxes.
run assigned macros and respond to events, such as
mouse clicks, by running Visual Basic for Applications Form controls
(VBA) code. Events associated with the controls can be
used to run a specific code to do a specific job. You use Form controls when you want to easily reference
and interact with cell data without using VBA code, and
For added flexibility, you can add controls and other drawing when you want to add controls to chart sheets. For
objects to the worksheet, and combine and coordinate example, after you add a list box control to a worksheet
them with worksheet cells. For example, you can use a and linking it to a cell, you can return a numeric value for
list box control to make it easier for a user to select from the current position of the selected item in the control.
a list of items. Or, you can use a spin button control to You can then use that numeric value in conjunction with
make it easier for a user to enter a number. the INDEX function to select different items from the list.

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.

You can also control different events that occur when an


ActiveX control is interacted with. For example, you can
perform different actions, depending on which choice a
user selects from a list box control, or you can query a
database to refill a combo box with items when a user
clicks a button. You can also write macros that respond
to events associated with ActiveX controls. When a user
of the form interacts with the control, your VBA code then
Form controls are built in to Excel whereas ActiveX controls runs to process any events that occur for that control.
are loaded from separate Dynamic Link Libraries.

83

Copyright Free under CC BY Licence


Table 1

Control Name Example Description

Label Identifies the purpose of a cell or text box, or displays descriptive text (such
as titles, captions, pictures) or brief instructions.
Group box Groups related controls into one visual unit in a rectangle with an optional
label. Typically, option buttons, check boxes, or closely related contents are
grouped.
Button Runs a macro that performs an action when a user clicks it. A button is also
referred to as a push button.
Check box Turns on or off a value that indicates an opposite and unambiguous choice.
You can select more than one check box on a worksheet or in a group box. A
check box can have one of three states: selected (turned on), cleared (turned
off), and mixed, meaning a combination of on and off states (as in a multiple
selection).
Option button Allows a single choice within a limited set of mutually exclusive choices; an
option button is usually contained in a group box or a frame. An option button
can have one of three states: selected (turned on), cleared (turned off), and
mixed, meaning a combination of on and off states (as in a multiple selection).
An option button is also referred to as a radio button.
List box Displays a list of one or more items of text from which a user can choose.
Use a list box for displaying large numbers of choices that vary in number or
content. There are three types of list boxes:
A single-selection list box enables only one choice. In this case, a list box
resembles a group of option buttons, except that a list box can handle a large
number of items more efficiently.
A multiple-selection list box enables either one choice or contiguous (adjacent)
choices.
An extended-selection list box enables one choice, contiguous choices, and
non-contiguous (or disjointed) choices.
Combo box Combines a text box with a list box to create a drop-down list box. A combo
box is more compact than a list box but requires the user to click the down
arrow to display the list of items. Use a combo box to enable a user to either
type an entry or choose only one item from the list. The control displays the
current value in the text box, regardless of how that value is entered.
Scroll bar Scrolls through a range of values when you click the scroll arrows or drag the
scroll box. In addition, you can move through a page (a preset interval) of
values by clicking the area between the scroll box and either of the scroll
arrows. Typically, a user can also type a text value directly into an associated
cell or text box.
Spin button Increases or decreases a value, such as a number increment, time, or date.
To increase the value, click the up arrow; to decrease the value, click the
down arrow. Typically, a user can also type a text value directly into an
associated cell or text box.

Your computer also contains many ActiveX controls that However, Active X controls cannot be added to chart sheets
were installed by Excel and other programs, such as from the user interface or to XLM macro sheets. You also
Calendar Control 12.0 and Windows Media Player. cannot assign a macro to run directly from an ActiveX
control the same way you can from a Form control. The
Not all ActiveX controls can be used directly on worksheets, summary of the Active X controls is given in Table 2. The
some can be used only on Visual Basic for Applications properties and events of commonly used ActiveX controls
(VBA) UserForms. If you try to add any one of these are shown in Table 3.
particular ActiveX controls to a worksheet, Excel displays
the message "Cannot insert object."

84 IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.105A - 2.2.105D

Copyright Free under CC BY Licence


Table 2

Control Name Example Description


Check box Turns on or off a value that indicates an opposite and unambiguous choice.
You can select more than one check box at a time 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).
Text box Enables you to, in a rectangular box, view, type, or edit text or data that is
bound to a cell. A text box can also be a static text field that presents read-
only information.
Command button Runs a macro that performs an action when a user clicks it. A command
button is also referred to as a push button.
Option button Allows a single choice within a limited set of mutually exclusive choices
usually contained in a group box or 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
noncontiguous (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 to allow 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.
Toggle button Indicates a state, such as Yes/No, or a mode, such as On/Off. The button
alternates between an enabled and disabled state when it is clicked.
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 into an associated
cell or text box.
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.
Label Identifies the purpose of a cell or text box, displays descriptive text (such as
titles, captions, pictures), or provides brief instructions.
Image Embeds a picture, such as a bitmap, JPEG, or GIF.
Frame control A rectangular object with an optional label that groups related controls into
one visual unit. Typically, option buttons, check boxes, or closely related
contents are grouped in a frame control.
Note The ActiveX frame control is not available in the ActiveX Controls section
of the Insert command. However, you can add the control from the More
Controls dialog box by selecting Microsoft Forms 2.0 Frame.
More Controls Displays a list of additional ActiveX controls available on your computer that
you can add to a custom form, such as Calendar Control 12.0 and Windows
Media Player. You can also register a custom control in this dialog box.

IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.105A - 2.2.105D 85

Copyright Free under CC BY Licence


Table 3

Control Name Properties in addition to the Some of the common events for the control
applicable properties mentioned
above

Check box GroupName,TripleState, Value, Change, Click, DblClick, GotFocus, LostFocus,


WordWrap etc. KeyPress etc.

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

Option button GroupName,TripleState, Value, Change, Click, DBLClick, GotFocus, LostFocus,


WordWrap etc. 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.

Methods: AddItem, Clear, RemoveItem

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.

Label Caption, SpecialEffect, TextAlign, Click, DBLClick, GotFocus, LostFocus etc.


WordWrap etc.

Image Picture, PictureSizeMode, Click, DBLClick, GotFocus, LostFocus etc.


PictureTiling, SpecialEffect etc.

Methods: LoadPicture(RunTime)

Frame control Cycle, KeepScrollBarsVisible, RedoAction, UndoAction, Repaint, Scroll,


PictureSizeMode, PictureTiling, Set Default Tab Order
Scrollbars, Zoom etc.

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.

The Methods common to most of the controls are Activate,


Copy, Cut, Delete, Select, Update etc.

86 IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.105A - 2.2.105D

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.106A & 2.2.106B
COPA - Programming with VBA

Workbook and worksheet objects


Objectives: At the end of this lesson you shall be able to
• describe collections in VBA
• describe the properties, events and methods of the workbook object
• describe the properties, events and methods of the worksheet ojbect.

Collections Workbook Object

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.

Some of the methods of Work Book are shown in Table 2

Table 2

Activate Activates the first window associated with the workbook.

Close Closes the object.

Protect Protects a workbook so that it cannot be modified.

Save Saves changes to the specified workbook.

SaveAs Saves changes to the workbook in a different file.

87

Copyright Free under CC BY Licence


Some of the events of WorkBook are shown in Table 3.

Table 3

Activate Occurs when a workbook, worksheet, chart sheet, or embedded chart is activated.

Open Occurs when the workbook is opened.

Worksheet Object The Worksheet object is also a member of the Sheets


collection. The Sheets collection contains all the sheets
The Worksheet object is a member of the Worksheets in the workbook (both chart sheets and worksheets).Some
collection. The Worksheets collection contains all the of the properties of WorkSheet are shown in Table 4.
Worksheet objects in a workbook.
Table 4

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.

Range Returns a Range object that represents a cell or a range of cells.

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.

Sort Returns a Sort object. Read-only.

Visible Returns or sets an XlSheet Visibility value that determines whether the object is visible.

Some of the methods of WorkSheet are shown in Table 5

Table 5

Activate Makes the current sheet the active sheet.

Copy Copies the sheet to another location in the workbook.

Delete Deletes the object.

PrintOut Prints the object.

SaveAs Saves changes to the chart or worksheet in a different file.

Select Selects the object.

ShowDataForm Displays the data form associated with the worksheet.

88 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.106A & 2.2.106B

Copyright Free under CC BY Licence


Some of the events of WorkSheet are shown in Table 6

Table 6

Activate Occurs when a workbook, worksheet, chart sheet, or embedded chart is activated.

Calculate Occurs after the worksheet is recalculated, for the Worksheet object.

Change Occurs when cells on the worksheet are changed by the user or by an external link.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.106A & 2.2.106B 89

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.107A
COPA - Programming with VBA

VBA Data types, Variables and Constants


Objectives: At the end of this lesson you shall be able to
• list the data types in VBA
• declare variables and assign values
• describe the option explicit statement.

Introduction 1 Memory & Calculation Speed: If you do not declare


a variable to have a data type, it will, by default, have
Variables are entities that hold data. In VBA, variables are the Variant type. This takes up more memory than many
areas allocated by the computer memory to hold data. of the other data types. Sometimes, Variant data types
The following are the variable naming rules in VBA: also take more time to process and at times may slow
down the process.
a Variable Names
2 Prevention of typing errors: If you always declare
The following are the rules when naming the variables in your variables, then you can use a VBA option to force
VBA you to declare variables. This will prevent you from
introducing errors in your code by accidentally typing
1 A Variable name must start with a letter and not a a variable name incorrectly.
number. Numbers can be included within the name, 3 Highlighting wrong Data Values: If you declare a
but not as the first character. variable to have a specific data type, and you attempt
2 A Variable name can be no longer than 250 characters. to assign the wrong type of data to it, this will generate
an error in your program.
3 A Variable name cannot be the same as any one of
Excel's key words. For ex. you cannot name a Variable The Option Explicit Statement
with such names as Sheet, Worksheet etc.
The option 'Explicit' forces you to declare all variables that
4 All Variables must consist of one continuous string of you use in your VBA code, by highlighting any undeclared
characters only. You can separate words by using the variables as errors during compilation (before the code will
underscore. run). To use this option, simply type the line as the very
b Declaring Variables first line of the program (In the General Declarations
section).
In VBA, the variables are declared before using them by
assigning names and data types. Declaring variables before If you select the 'Require Variable Declaration' option of
use tells the computer to allocate a certain memory for your VBA editor, the statement'Option Explicit' is always
the variable data to be placed. Though it is a good practice automatically included at the top of every new VBA module
to declare variables before use, in Visual Basic it is not that is created.
actually compulsory to specifically declare a variable before
it is used. If a variable isn't declared, VB will automatically To do this:
declare the variable as a Variant. A variant is data type
that can hold any type of data. • In the Visual Basic Editor, select Tools  Options...
• Ensure the Editor tab is selected
To declare a variable we use the word "Dim" (short for
Dimension) followed by our chosen variable name then • Check the box next to the option Require Variable
the word "As" followed by the variable type. For ex. Dim n Declaration and click OK
as Integer.
Keywords
You may also combine more variables to be declared in
one line, separating each variable with a comma, as follows: Keywords in Excel VBA are words that Excel has set
aside to use in the execution of code. This means we
Dim first_name As String, joining_date As Date, Pay As cannot use them for any other purpose. For example,
Integer. Select, Active, Sub, End, Function etc are all Keywords
that we can only use for their intended purpose.
Declaring a variable before use is a good programming
practice for the following reasons: Some of the reserved keywords are shown in Table 1.

90

Copyright Free under CC BY Licence


Table 1

ByVal Call Case CBool CByte CDate

CDbl CInt CLng Const CSng CStr

Date Dim Do Double Each Else

ElseIf End EndIf Error False For

Function Get GoTo If Integer Let

Lib Long Loop Me Mid Mod

New Next Not Nothing Option Or (Bitwise)

Or (Condition) Private Public ReDim REM Resume

Select Set Single Static Step String

Sub Then To True Until vbCrLf

vbTab With While Xor

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

Type Storage Range of Values

Byte 1 byte 0 to 255

Integer 2 bytes -32,768 to 32,767

Long 4 bytes -2,147,483,648 to 2,147,483,648

Single 4 bytes -3.402823E+38 to -1.401298E-45 for negative values

1.401298E-45 to 3.402823E+38 for positive values.

Double 8 bytes -1.79769313486232e+308 to -4.94065645841247E-324 for negative values

4.94065645841247E-324 to 1.79769313486232e+308 for positive values.

Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807

Decimal 12 bytes +/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use

+/- 7.9228162514264337593543950335 (28 decimal places).

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.107A 91

Copyright Free under CC BY Licence


Non Numeric Data Types data types, the Date data types, the Boolean data types
that store only two values (true or false), Object data type
Non-numeric data types are data that cannot be and Variant data type.The non numeric data types are
manipulated mathematically using standard arithmetic summarized in Table 3.
operators. The non-numeric data comprises text or string

Table 3

Data Type Storage Range

String(fixed length) Length of string 1 to 65,400 characters

String(variable length) Length + 10 bytes 0 to 2 billion characters

Date 8 bytes January 1, 100 to December 31, 9999

Boolean 2 bytes True or False

Object 4 bytes Any embedded object

Variant(numeric) 16 bytes Any value as large as Double

Variant(text) Length+22 bytes Same as variable-length string

Enumerated Data Types Suffixes for Literals

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:

Windows Dim marks% 'integer

Linux Dim gorss_pay& 'long

Unix Dim Average! 'single

DOS Dim Total# 'double

MAC Dim Profit@ 'currency

End Enum Dim FirstName$ 'string

92 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.107A

Copyright Free under CC BY Licence


If the data type is not specified, VB will automatically Variable = Expression
declare the variable as a Variant.
The variable can be a declared variable or a control's
Named Constants property value. The expression could be a mathematical
expression, a number, a literal value, a string, a Boolean
If you have a value that never changes in your application, value (true or false) , a combination of other variables and
you can define a named constant and use it in place of a constants, a function and more. The following are some
literal value. A name is easier to remember than a value. examples:
You can define the constant just once and use it in many
places in your code. If in a later version you need to redefine Basic = 10000
the value, the Const statement is the only place you need
to make a change. DA = Basic * 0.9

You can use Const only at module or procedure level. First Name = "Uma"
This means the declaration context for a variable must be
a class, structure, module, procedure, or block, and cannot Label1.Caption = "Enter your age"
be a source file, namespace, or interface
Command 1 Visible = false
Example:Const Pi As Single=3.142
Textbox.multiline = True
Assigning Values to Variables
Label 1 Caption = textbox1.Text
After declaring various variables using the Dim keywords
or other keywords, we need to assign values or information A type mismatch error occurs when you try to assign a
to those variables. Assigning a value to a variable means value to a variable of incompatible data type.
storing the value in that variable. The form of an assignment
statement is as follows:

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.107A 93

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.107B
COPA - Programming with VBA

Operators in VBA and operator precedence


Objectives : At the end of this lesson you shall be able to
• explain the various operators and their precedence in VBA.

Operators in VBA • Logical (or Relational) Operators


An Operator can be defined using a simple expression - • Concatenation Operators
4 + 5 is equal to 9. Here, 4 and 5 are called operands and
+ is called operator. VBA supports following types of The Arithmetic Operators
operators “
Following arithmetic operators are supported by VBA.
• Arithmetic Operators
Assume variable A holds 5 and variable B holds 10, the
• Comparison Operators results of the various operators as shown in Table 1.
Table 1

Operator Description Example

+ Adds the two operands A + B will give 15

- Subtracts the second operand from the first A - B will give -5

* Multiplies both the operands A * B will give 50

/ Divides the numerator by the denominator B / A will give 2

% Modulus operator and the remainder after an


integer division B % A will give 0
^ Exponentiation operator B ^ A will give 100000

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

Operator Description Example

= Checks if the value of the two operands are equal or not.


If yes, then the condition is true (A = B) is False

<> 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

>= Checks if the value of the left operand is greater than or


equal to 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 or


equal to the value of the right operand. If yes, then the
condition is true (A <= B) is True

94

Copyright Free under CC BY Licence


The Logical Operators Assume variable A holds 10 and variable B holds 0, the
results on the various logical operators shown in Table 3
Following logical operators are supported by VBA.
Table 3

Operator Description Example

AND Called Logical AND operator. If both the conditions are


True, then the Expression is true a<>0 AND b<>0 is False

OR Called Logical OR Operator. If any of the two conditions are


True, then the condition is true a<>0 OR b<>0 is true

NOT Called Logical NOT Operator. Used to reverse the logical


state of its operand. If a condition is true, then Logical NOT
operator will make false NOT(a<>0 OR b<>0) is false

XOR Called Logical Exclusion. It is the combination of NOT and


OR Operator. If one, and only one, of the expressions
evaluates to be True, the result is True. (a<>0 XOR b<>0) is true

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

Operator Description Example

+ Adds two Values as Variable. Values are Numeric A + B will give 15

& Concatenates two Values A & B will give 510

Assume variable A = “Microsoft” and variable B =


“VBScript”, the result of the various concatenation shown
in Table 5
Table 5

Operator Description Example

+ Concatenates two Values A + B will give MicrosoftVBScript

& Concatenates two Values A & B will give MicrosoftVBScript

Note: Concatenation Operators can be used for


both numbers and strings. The output depends
on the context, if the variables hold numeric
value or string value.

Precedence expression. Operations inside parentheses are always


performed before those outside.
When several operations occur in an expression, each
part is evaluated and resolved in a predetermined order When a series of operators appear in the same expression
called operator precedence. there is a strict order in which they will be evaluated.

When operators have the same precedence they are The rules of precedence tell the compiler which operators
evaluated from left-to-right.Parentheses can be used to to evaluate first.
override the order and to evaluate certain parts of the

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.107B 95

Copyright Free under CC BY Licence


Parentheses can obviously be used to change the order Operators are evaluated in the following order:
of precedence. Mathematical, Concatenation, Relational, Logical.

The table 6 shows the precedence order of operators.

Table 6

Order Operator Symbol

1 Exponentiation ^

2 Negation -

3 Multiplication *

3 Division /

4 Division with Integer result \

5 Modulo Mod

6 Addition +

6 Subtraction -

7 String Concatenation &

8 Equal or Assignment =

8 Not Equal To <>

8 Less Than <

8 Greater Than >

8 Less Than or Equal To <=

8 Greater Than or Equal To >=

9 Not NOT

10 And AND

11 Or OR

12 Exclusive OR XOR

13 Equivalence EQV

14 Implication IMP

The table 7 shows the expression, steps to evaluate and


the result.

Expression First Step Second Step Third Step Result

3^(15/5)*2-5 3^3*2-5 27*2-5 54-5 49


3^((15/5)*2-5) 3^(3*2-5) 3^(6-5) 3^1 3
3^(15/(5*2-5)) 3^(15/(10-5)) 3^(15/5) 3^3 27

96 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.107B

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.108
COPA - Programming with VBA

VBA Message boxes and Input boxes


Objectives: At the end of this lesson you shall be able to
• state the uses of message boxes and input boxes in VBA
• describe the msgbox method and msgbox function
• describe the inputbox method and inputbox function.

Introduction Customize the buttons in a VBA message box

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 MsgBox Method End Sub

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.

The basic form of the Message Box (msgbox) in VBAis


:Msgbox("message")

Example:

Sub result()

Msgbox("congratulations")

End sub

This displays a message box as shown in Fig 1


The MsgBox Function
Fig 1
The MsgBox Function displays a message in a dialog
box, waits for the user to click a button, and then returns
an integer indicating which button was clicked by the
user.The syntax of the Msgbox() function is :

Return value = MsgBox(Prompt, Button and Icon types,


Title, Help File, Help File Context)

97

Copyright Free under CC BY Licence


Table 1
Constant Description

vbOKOnly It displays a single OK button

vbOKCancel It displays two buttons OK and Cancel.

vbAbortRetryIgnore It displays three buttons Abort, Retry, and Ignore.

vbYesNoCancel It displays three buttons Yes, No, and Cancel.

vbYesNo It displays two buttons Yes and No.

vbRetryCancel It displays two buttons Retry and Cancel.

vbCritical It displays a Critical Message icon.

vbQuestion It displays a Query icon.

vbExclamation It displays a Warning Message icon.

vbInformation It displays an Information Message icon.

vbDefaultButton1 First button is treated as default.

vbDefaultButton2 Second button is treated as default.

vbDefaultButton3 Third button is treated as default.

vbDefaultButton4 Fourth button is treated as default.

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.

vbMsgBoxHelpButton This adds a Help button to the message box.

VbMsgBoxSetForeground Ensures that message box window is foreground.

vbMsgBoxRight This sets the Text to right aligned

vbMsgBoxRtlReading This option specifies that text should appear as right-to-left.

Where: Values returned by MsgBox Function:

Return Value: Indicates the action the user took when VBA MsgBox function returns a value based on the user
the message box was shown to him/her. input. These values can be anyone of the ones shown in
Table 2.
Prompt : It is the message contained in the main body of
the message box. A Msgbox function example is shown in the code
mentioned below.
Button and Icon Types : This specifies the set of buttons
& Icons and their placement as they would appear to the Sub test()
user.
Dim n As Integer
Help File : This is the path to a help file that the user can
refer to on this topic. n = MsgBox("Do you want to print this file?", vbYesNo,
"Action on Files")
Help File Context : This is the pointer to that part of the
help file that specifically deals with this message. End Sub
98 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.108

Copyright Free under CC BY Licence


Table 2 Sub test()

Value Description Dim n As Integer

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.

Note that Application.Input Box calls the Input Box method;


Input Box with no object qualifier calls the InputBox
function.

Input Box Function

The Input Box Function displays a dialog box for user


input. It returns the information entered in the dialog box.
Reading the Msgbox() return values The syntax for the InputBox function is:

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

Its Syntax is :Input Box(Prompt, Title, Default, Left, Top,


HelpFile, HelpContextId, Type)

The Prompt, Title and Default are the same as in the


InputBox Function. However, it is the last argument "Type"
that allows us to specify the type of data we are going to
collect. These are as shown below.

Type:=0 A formula

Type:=1 A number

Type:=2 Text (a string)

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.108 99

Copyright Free under CC BY Licence


Type: = 4 A logical value (True or False) n = Application.InputBox("Enter you age", "Personal
Details", , , , , , 1)
Type: = 8 A cell reference, as a Range object
'Exit sub if Cancel button used
Type: = 16 An error value, such as #N/A
If n > 60 Then
Type := 64 An array of values
MsgBox "You are eligible for senior citizen's concession"
The following is an example of an InputBox method
Else
Sub test()
MsgBox ("No concession")
Dim n As Integer
End If

End Sub

100 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.108

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.109A - 2.2.109C
COPA - Programming with VBA

Decision making statements in VBA


Objectives: At the end of this lesson you shall be able to
• describe the decision making process using the “if... Then” statement
• describe the use of “ladder off” and “nested if” statement
• explain the use of the “select ....case” statements.

Introduction The flow chart for a typical If statement is shown in Fig 1.

In a program a set of statements are normally executed


Fig 1
sequentially in the order in which they appear. This
happens when no decision making or repetitions are
Inial Value
involved. But in reality, there may be a number of situations
where we may have to change the order of execution of
statements based on certain conditions being true or false.
Some of the examples may be: Yes
Check condion
a To decide if a trainee is to be declared "Passed" or
"Failed".
b To display the Grade achieved by a student.
No
c To accept input only of a particular data type like
numbers.
d To decide if a number is prime or not.
e To decide if a string is a palindrome or not. Next code to run
f To calculate pay, tax, commission etc. based on
certain conditions etc.
g To repeat an action a certain number of times or till a Here condition refers to an expression which results in a
certain limit is reached. Boolean type result, ie. True or False.For ex. the
statement "if age <18" will test if the value of the variable
Decision making process can solve practical problems "age" is less than 18 or not. If the condition evaluates to
intelligently and provide useful output or feedback to the true, then the block of code inside the If statement will be
user. In order to control the program flow and to make executed. For example:
decisions, we need to use the conditional operators and
the logical operators together with the If control structure. If (age < 18) Then

Decision making structures require that the programmer debug.print "Not Eligible"
specify one or more conditions to be evaluated or tested
by the program, along with a statement or statements to End If
be executed if the condition is found to be true, and other
statements to be executed if the condition is found to be The following example tests the value of the number in the
false.Table 1 shows the commonly used decision making textbox and takes a decision.
statements in VBA.
Private Sub Button1_Click()
The If … Then Statement
Dim n As Integer
It is the simplest form of control statement, frequently used
in decision making and changing the control flow of the 'Enter the number of items sold by the agent
program execution. Syntax for if-then statement is:
n = val(TextBox1.Text)
If CONDITION Then
If n> 100 Then
' code if the condition is met
Label1.Caption = " You are entitled for a commission of
End If Rs. 10000"

101

Copyright Free under CC BY Licence


End If MsgBox "You need not pay any income tax"

End Sub Else

The If Then…. Else Statements Msg Box ("You must pay income tax")

When an action has to be taken if the condition returns End If


true and another action if the condition returns false, then
we use the If Then…. Else Statements. End Sub

The syntax for the If Then … Else statements is as follows Using Multiple If Statements

If CONDITION Then Sometimes the condition being tested is to be evaluated


not just for returning "True" or "False" based on one
' code if the condition is met condition, but for multiple conditions too. In such cases
the multiple If Then …. Else statements can be used.
Else They can be used in two ways:

' code if the condition is not met 1 Ladder If and


2 Nested if
End If
Ladder If statements
The flow chart for a typical If Then … Else structure is as
shown in Fig 2. The ladder if statements can be used to test if a condition1,
condition2 … etc is met, and decision be taken based on
Fig 2 which condition is met. The typical syntax of a Ladder If
structure is:
Inial Value
if(boolean_expression 1)

{
Check condion
/* Executes when the boolean expression 1 is true */

Yes No }

else if( boolean_expression 2)


Code A Code B
{

/* Executes when the boolean expression 2 is true */

}
Next code to run
else if( boolean_expression 3)

The example of an If Then … Else structure is shown {


below. This program tests if the Taxable Income entered
by the user is less than 250000 or not. If yes, a message /* Executes when the boolean expression 3 is true */
box appears stating that the user need not pay Income
Tax. Else, another message box tells the user to pay the }
tax.
else
Sub test()
{
Dim income As Long
/* executes when the none of the above condition is true
income = Application.InputBox("Enter you Taxable */
income")
}
If income< 250000 Then

102 IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.109A - 2.2.109C

Copyright Free under CC BY Licence


The following is an example of a ladder if structure. If the first condition is not met, the control jumps to the
statement after the End if statement. The following code
Sub grades()
is an example for the mentioned example.
Dim marks As Integer Sub job_test()
Dim experience, marks As Integer
marks = InputBox("Enter you marks")
experience = InputBox("Enter your work experience in
If marks >= 80 Then
years")
MsgBox "Distinction"
If experience >= 5 Then
ElseIf marks >= 70 Then
marks = InputBox("Enter you marks percentage")
MsgBox "A Grade"
If marks >= 75 Then
ElseIf marks >= 60 Then
MsgBox (" You are eligible for the post")
MsgBox "B Grade"
Else
ElseIf marks >= 40 Then
MsgBox (" You are NOT eligible for the post")
MsgBox "C Grade"
End If
Else
Else
MsgBox "Failed"
MsgBox (" You are NOT eligible for the post")
End If
End If
End Sub
End Sub
This program would display the grade based on the marks
Using Logical operators in If Structure
entered by the user.
The Logical operators And, Or and Not can be used in If
Nested If statements structure and produce the same results as those produced
Sometimes it is required to evaluate one condition only if in Nested If Structures.
an earlier condition is met. In such cases an If Then
For ex. the above mentioned condition can be evaluated
statement can be placed inside an outer If Then statement.
using the And operator in the conditional statement.
This type of structure is also called a Nested If
structure.The syntax of a nested if structure is as follows: Sub job_test()
If(Boolean_expression 1) Dim experience, marks As Integer
{ experience = InputBox("Enter your work experience in
years")
//Executes when the Boolean expression 1 is true
marks = InputBox("Enter you marks percentage")
If(Boolean_expression 2)
If experience >= 5 And marks >= 75 Then
{
MsgBox (" You are eligible for the post")
//Executes when the Boolean expression 2 is true Else

} MsgBox (" You are NOT eligible for the post")

} End If
End Sub
For ex. A certain recruitment condition states that a
candidate to be declared eligible must have a minimum of Select...Case
5 years' experience and also must have scored atleast Another way to implement decision making in your VBA
75% marks in the exam. In such a case, the first condition code is to use a Select...Case statement. Select...Case
to be tested is for experience >= 5 years andonly if this statements can be used to easily evaluate the same
condition is met, the second condition is to be evaluated. variable multiple times and then take a particular action
depending on the evaluation.
IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.109A - 2.2.109C 103

Copyright Free under CC BY Licence


It is always a good practice to use Select Case Statement This function is available within VBA code and also as an
when multiple If-Else conditions are involved. As the number Excel function. Usually the IIF function is used to perform
of If-Else conditions increases, debugging and quick logical assessments and can be nested to perform
understanding all the flow becomes a tedious job. more complicated evaluations. It is however important to
remember that nested IF statements can become very
The syntax for a Select...Case statement is: complicated and difficult to support and maintain.
Now let’s look at an example. Let’s assume that we want
Select Case VARIABLE
to calculate the length of the string only if it contains the
Case VALUE1 value Excel Help and Excel. (Fig 3)
Fig 3
' code to run if VARIABLE equals Value1

Case VALUE2

' code to run if VARIABLE equals Value2

Case Else

' code to run for remaining cases

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)

Case Else Fig 4

Debug.Print "I have no idea."


End Select
End Sub

IIF Function
IIF function is used to evaluate an expression and perform
one of two actions based on the outcome of the evaluation.
For example:

IIF (Value > 10, Perform this action if Value is <= 10,
Perform this action is Value is > 10)

104 IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.109A - 2.2.109C

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.110A & 2.2.110B
COPA - Programming with VBA

Looping statements in VBA


Objectives: At the end of this lesson you shall be able to
• describe the “for” loops in VBA
• describe the “do” loops in VBA
• explain the use of the “exit” statement in VBA loops
• write appropriate code to perform repetitive tasks.

Introduction is the same as For n = 1 To 10 Step 1 since the default


increment is 1
There may be many situations where you need to perform
a task repeatedly / a certain number of times. In such The same code will print numbers from 10 to 1 if the step
cases the code for the task is placed inside a loop and is changed to a negative value as shown below.
the program iterates or repeats through the loop a certain
number of times ie. till a certain condition is met. Some For n = 10 To 1 Step -1
examples of such repetitive tasks are:
debug. print n
a Printing a text or number n number of times.
Next n
b Generating a sequence or series of numbers.
c Generating a table of certain calculations. Similarly, the following Ex. would add all the numbers from
1 to 10 and print the sum.
d Searching / Re arranging a set of numbers etc.
VBA provides the following types of loops to handle looping Dim n, sum as integer
requirements (Refer Table 1)
Sum=0
Table 1
For n = 1 To 10
Loop Type Description
sum=sum + n
for next loop Execute a sequence of statements
multiple times and abbreviates the debug. print sum
code that manages the loop
variable. Next n

do....until loop Repeats a statement or group of The For Each Loop


statements until a condition is met.
The For Each loop is similar to the For ... Next loop but,
do….while loop Repeats a statement or group of instead of looping through a set of values for a variable, it
statements as long as the condition loops through every object within a set of objects. The
is true. following example would print the names of all the
worksheets.
The For Loop
Dim ws As Worksheet
The For ... next loop sets a variable to a specified set of
values, and for each value, runs the VBA code inside the For each ws in Worksheets
loop. For Ex.
debug. print ws.name
For n = 1 To 10
Next ws
debug.print n
The Exit For Statement
Next n
If you need to end the For loop before the end condition is
In this example, the initial value of n is set to 1, and the reached or met, simply use the END FOR in conjunction
loop code, ie. printing the value of n is performed.The value with the IF statement. In the example given below, we exit
of n is set to the next value which is by default an increment the for loop prematurely and before the end condition is
of 1. Thus this loop is executed 10 times and would print
the numbers 1 to 10. The for statement in the above code
105

Copyright Free under CC BY Licence


met. The for example given below, the loop exits when n b Execute the code in the loop and then test for the
reaches a value of 5. condition.
Do While ….Loop
For n = 0 To 10
In this example, the condition ie. num<10 is checked
debug.print n
before entering the loop. Only if the condition is met, the
code in the loop is executed, otherwise it is skipped
If n=5 Then Exit For
entirely. This example will print a table as shown in Fig 1.
Next n
Fig 1

The Do ….Until Loop repeats a statement or group of


statements until a condition is met.

There are 2 ways a Do Until loop can be used in Excel


VBA Macro code.

a Test the condition before executing the code in the


loop
b Execute the code in the loop and then test for the
condition.
Do Until….. Loop

In this example, the value of n is tested before going into


the loop.

If the condition n=10 is not met right at the beginning itself,


the code inside the loop is not executed at all. The control
then jumps to the statements appearing after the Loop
statement.

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.

a Test the condition before executing the code in the


loop

106 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.110A & 2.2.110B

Copyright Free under CC BY Licence


Fig 2 Dim Counter

Previous code Counter = 0

While Counter < 5

Counter = Counter + 1
Loop code
Debug.Print "hello"

Wend

Debug.Print Counter

No The Exit Statement

Yes The Exit Statement exits a procedure or block and transfers


control immediately to the statement following the
Next code to procedure call or the block definition. It may be in the form
of Exit Do, Exit For, Exit While, Exit Select etc. depending
on where it is being used. An example of an Exit statement
is as follows:
Dim row As Integer
Do While True
row = 0
Count = Count + 1
Do
Debug.Print Count
row = row + 1
If Count = 5 Then
Cells(row, 1) = row
Debug.Print "stop at 5"
Loop While row < 10
Exit Do
The While ….. Wend loop
End If
The While ….. Wend loop executes a series of statements
as long as a given condition is True. Loop

In this example the condition checking is done at the In this example, the loop condition stops the loop when
beginning of the loop. This code prints hello 5 times and count=5.
then prints the value of the counter, ie. 5 at the end of the
program.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.110A & 2.2.110B 107

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.111A - 2.2.111C
COPA - Programming with VBA

Arrays in VBA
Objectives: At the end of this lesson you shall be able to
• describe and declare an array in VBA
• differentiate between static and dynamic arrays
• declare, populate and read a multidimensional array
• describe the redim and preserve statements in VBA.

Introduction Dim StudentName(3) As String

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.

Types of Arrays : Dim arr()()() As integer

1 Static Arrays In VBA arrays you can specify any value for the lower and
upper bounds of the array. Element 0 need not be the first
2 Dynamic Arrays element in the array. For example, the following is perfectly
Static array legal code (as long as the lower bound is less than or
equal to the upper bound -- an error is generated if the
A static array is an array that is sized in the Dim statement lower bound is greater the upper bound).
that declares the array. E.g.,
If you don't explicitly declare the lower bound of an array,
Dim Students(10) as String the lower bound will be assumed to be either 0 or 1,
depending on value of the Option Base statement, if
Dim StaticArray(1 To 10) As Long present. If Option Base is not present in the module, 0 is
assumed. For example, the code
You cannot change the size or data type of a static array.
When you erase a static array, no memory is freed. Erase Dim Arr(10) As Long
simply sets all the elements to their default value (0,
vbNullString, Empty, or Nothing, depending on the data declares an array of either 10 or 11 elements. The
type of the array). declaration does not specify the number of elements in
the array. Instead, it specifies the upper bound of the array.
Declaring an Array If your module does not contain an "Option Base"
statement, the lower bound is assumed to be zero,
You declare an array variable using the Dim statement. and the declaration above is the same as :
Dim Arr(0 To 10) As Long

108

Copyright Free under CC BY Licence


If you have an Option Base statement of 0 or 1, the lower Here LBound() and UBound() functions return the Lower
bound of the array is set to that value. and Upper Bounds of the Array.

Thus, the code : Dim Arr(10) As Long is the equivalent of Multi dimensional Arrays
either Dim Arr(0 To 10) As Long or Dim Arr(1 To 10) As
Long, depending on the value of the Option Base. Multi dimensional arrays have more than one row or one
column.
It is a good programming practice to specify both the lower
and upper bounds of the array to avoid bugs when copying For ex.Dim MyArray(5, 4) As Integer
and pasting code between modules or elsewhere.
Dim MyArray(1 To 5, 1 To 6) As Integer
Storing values in an array
In the following ex. we will define an array with 3 elements
Arrays can be populated in the following ways each in two rows

1 Marks(0)=55 Sub array_test()


Marks(1)=67
Sub array_test()
Marks(2)=55
Dim m, n As Integer
Marks(3)=67
Marks(4)=74 Dim arr(2, 4) As String
2 Dim marks As Integer() = {55, 67, 87, 48, 90, 74} arr(0, 0) = "printer"
3 Dim marks = New Integer() {1, 2, 4, 8}
arr(0, 1) = "scanner"
4 Dim doubles = {1.5, 2, 9.9, 18}
You can explicitly specify the type of the elements in an arr(0, 2) = "mouse"
array that's created by using an array literal. In this case,
the values in the array literal must widen to the type of the arr(0, 3) = "monitor"
elements of the array. The following code example creates
an array of type Double from a list of integers: Dim marks arr(1, 0) = "usb"
As Double() = {55, 67, 87, 48, 90, 74}
arr(1, 1) = "ps2"
Iterating through an Array
arr(1, 2) = "firewire"
Loop statements like for… next, Do …while etc. can be
used with arrays to retrieve their values.An example of arr(1, 3) = "serial"
such a code is shown below.
For m = 0 To 2
Sub array_test()
For n = 0 To 3
Dim arr(5) As Integer
Debug.Print arr(m, n); Spc(2);
Dim n As Integer
Next n
arr(0) = 89

arr(1) = 56 Debug.Print

arr(2) = 78 Next m

arr(3) = 45 End Sub


arr(4) = 99 Dynamic Arrays
For n = LBound(arr) To UBound(arr) - 1
A dynamic array is an array that is not sized in the Dim
Debug.Print arr(n) statement. Instead, it is sized with the ReDim statement.
Dynamic array variables are useful when we don't know in
Next advance how many elements need to be stored in the
array or when we need to change the array dimensions at
End Sub
a later stage.

IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.111A - 2.2.111C 109

Copyright Free under CC BY Licence


E.g. : Dim DynamicArray() As Long A(3) = "MASE"

ReDim DynamicArray(1 To 10) debug.print A(1) & " , " & A(2) & " , " & A(3)

If an array is sized with the ReDim statement, the array is End Sub
said to be allocated( either static array or a dynamic
array).Static arrays are always allocated and never When you use the ReDim keyword, you erase any existing
empty.You can change the size of a dynamic array, but data currently stored in the array.
not the data type. When you Erase a dynamic array, the
memory allocated to the array is released. You must For ex. add another element to the array mentioned in
ReDim the array in order to use it after it has been Erased. the example above using the redim statement as follows
and assign a value to it.
If a dynamic array has not yet been sized with the ReDim
statement, or has been deallocated with the Erase ReDim A(4) As String
statement, the array is said to be empty or unallocated.
Static arrays are never unallocated or empty. A(4) = "CHNM"

ReDim Statement: Now when the array values are displayed again, the earlier
values will all be blank, since they are erased by the redim
You may declare a dynamic variable with empty statement. The example below shows this:
parentheses ie. leave the index dimensions blank. You
can thereafter size or resize the dynamic array that has Sub arr_test()
already been declared, by using the ReDim statement. To
resize an array, it is necessary to provide the upper bound, 'declare a dynamic array
while the lower bound is optional. If you do not mention
the lower bound, it is determined by the Option Base Dim A() As String
setting for the module, which by default is 0. You can
specify Option Base 1 in the Declarations section of the ReDim A(3) As String
module and then index will start from 1. This will mean
that the respective index values of an array with 3 elements A(1) = "COPA"
will be 1, 2 and 3. Not entering Option Base 1 will mean
A(2) = "DTPO"
index values of 0, 1 and 2.
A(3) = "MASE"
The following example declares an array called A1 as a
dynamic array. The array's size is not set and then it is
ReDim A(4) As String
resized to 3 elements (by specifying Option Base 1)
A(4) = "CHNM"
Sub arr_test()
Debug.Print A(1) & " , " & A(2) & " , " & A(3) & "," & A(4)
'declare a dynamic array
End Sub
Dim A() As String
The result of this program will be , , ,CHNM
ReDim A(3) As String
To resize the array without losing the existing data, you
A(1) = "COPA"
should use " Preserve " along with Redim. For ex. ReDim
Preserve A(4) As String.
A(2) = "DTPO"

110 IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.111A - 2.2.111C

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.112
COPA - Programming with VBA

String manipulation in VBA


Objectives: At the end of this lesson you shall be able to
• describe the string concatenation functions in VBA
• describe the string conversion functions in VBA
• describe the string extraction functions in VBA
• describe the string formatting functions in VBA.

Introduction This will print: The payment for Jaya is 25000

A string, in VBA, is a type of data variable which can Len() function


consist of text, numerical values, date and time and
alphanumeric characters. Strings are a frequently used to Returns an integer containing either the number of
store all kinds of data and are important part of VBA characters in a string or the nominal number of bytes
programs. To declare a variable for it, you can use either required to store a variable.
String or the Variant data types.
Syntax : Len (String)
String Manipulation
Example : 1
VBA has a robust set of functions for string handling. The
following are some examples of where you might use string Dim str As String
functions:
str = "Computer operator and programming assistant"
• Checking to see whether a string is contained another
string Debug.Print "The length of the string is "& Len(str)
• Parsing out a portion of a string This will print : The length of the string is 43
• Replacing parts of a string with another value
Example : 2
• Finding the length of the string etc.
String Concatenation Dim p, q As Integer, r As Double, dob As Date

String concatenation or joining two or more strings can be p = Sqr(25)


done by the "+" Operator
q = 3333
Example : Dim A, B, C As String
r = 45.6789
A = "www"
dob = #1/1/1990#
B = " and"
Debug.Print "Size of p Is : " & Len(p)
C = " the Internet"
Debug.Print "Size of q Is : " & Len(q)
Debug.Print A + B + C
Debug.Print "Size of r Is : " & Len(r)
This will print "www and the Internet"
Debug.Print "Size of dob Is : " & Len(dob)
If it is required to join two or more different data types
variable, then the "&" operator can be used. Thiswill print : Size of p Is : 1

Example : Dim person As String, pay As Integer Size of q Is : 2

person = "Jaya" Size of r Is : 8

pay = 25000 Size of dob Is : 8

Debug.Print "The payment for "& person & " is " & pay

111

Copyright Free under CC BY Licence


Left() RTrim()

Returns a string containing a specified number of Returns a string containing a copy of a specified string
characters from the left side of a string. with no trailing spaces.

Syntax: Left(String ,Int) Syntax :RTrim(String)

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" &LTrim(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

Syntax: Mid(String, Int, Int) For everyone Adjustmentis a must

For everyone Adjustmentis a must


Returns a string that contains a specified number of
characters starting from a specified position in a Instr()
string.Examples are :
Returns an integer specifying the start position of the first
1 Dim s AsString occurrence of one string within another.
s =" Indiana Jones" Syntax: InStr([start, ]string1, string2[, compare])
debug.print Left(s)
Example:
This will print : India
A = "hairdresser"
2 Dim s AsString
s =" FUNDAMENTALLY" B = "dress"

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

s =" wholehearted" Replacing Strings


debug.print mid(s, 6) The Replace() function replaces a sequence of characters
This will print : hearted in a string with another set of characters.
4 Dim s AsString Replace(source_string, find_string, replacement_string).
s =" wholehearted" Eample: Debug.Print Replace("majordrawback",
debug.print mid(s, 6,4) "drawback", "advantage")
This will print : hear Debug.Print Replace("majority", "aj", "in", 1)
Ltrim()
Debug.Print Replace("think and think", "i", "a", 1, 1)
Returns a string containing a copy of a specified string This will print : major advantage
with no leading spaces (LTrim)
minority
Syntax :LTrim(String)
thank and think

112 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.112

Copyright Free under CC BY Licence


Val() CStr()

The VAL() function accepts a string as input and returns The CStr() function is used to convert any type of value to
the numbers found in that string.The VAL function will stop a string.
reading the string once it encounters the first non-numeric
character. This does not include spaces. Syntax: Str(number as variant)

Syntax: Val(String) Example:

Example: Dim s1, s2, s3 As String 1 Dim Number As Double


Number = 1450.5
s1 = "6 feet 1 inch is his height"
Debug.Print "The string is "&str(Number)
s2 = "5 - 6 kms is the distance to my office from here"
This will print : The string is 1450.5
s3 = "011 22222222 is my telephone number" 2 Dim Date_of_birthAs Date
Date_of_birth = #1/1/1990#
Debug.Print Val(s1)
Debug.Print CStr(Date_of_birth)
Debug.Print Val(s2)
This will print : 01/01/1990
Debug.Print Val(s3) Asc()

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

1122222222 Syntax :Asc(String)

The String Conversion Functions Example :Asc("A") will return 65

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

B = "be a strong person" A = "desserts"

Debug.PrintLcase(A) Debug.Print StrReverse(A)

Debug.PrintUCase(B) This will print : stressed

This will print: if you fear you will become weak Format() function

BE A STRONG PERSON The format() function returns a Variant (String) containing


an expression formatted according to instructions contained
Str() in a format expression. It can be used to return formatted
dates as well as formatted strings.
The Str() function converts a number to a string.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.112 113

Copyright Free under CC BY Licence


Syntax(for FormattingStrings) : Format(String, Format) You can use any of the following characters to create a
format expression for strings:
User-Defined String Formats (Format Function)
Example :Dim x As String

Character Description

@ Character placeholder. Display a character or a space. If the string has a character in the
position where the at symbol (@) appears in the format string, display it; otherwise,
display a space in that position. Placeholders are filled from right to left unless there is an
exclamation point character (!) in the format string.

& Character placeholder. Display a character or nothing. If the string has a character in the
position where the ampersand (&) appears, display it; otherwise, display nothing.
Placeholders are filled from right to left unless there is an exclamation point character (!)
in the format string.

< Force lowercase. Display all characters in lowercase format.

> Force uppercase. Display all characters in uppercase format.

! Force left to right fill of placeholders. The default is to fill placeholders from right to left.

x = "change case"

Debug.Print Format(x, ">")

This will print "CHANGE CASE"

114 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.112

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.113
COPA - Programming with VBA

Built in Functions in VBA


Objectives: At the end of this lesson you shall be able to
• describe the math functions in VBA
• describe the logical functions in VBA
• describe the date/time functions in VBA
• describe the conversion functions in VBA.

Introduction MS Excel: VBA Functions (VBA Formulae) - Category


wise
VBA has a rich collection of built in functions that perform
a variety of tasks and calculations for you. There are The commonly used VBA functions in Excel, sorted by
functions to convert data types, perform calculations on Category are shown here.
dates, perform simple to complex mathematics, make
financial calculations, manage text strings, format values, String Functions: The string functions were already
and retrieve data from tables, among others. Using the discussed in the related theory for Ex. 2.2.09
VBA Built in Functions will help coding much easier for
the user. We have already used many built in functions in Math Functions
our earlier lessons like the msgbox function and many
string manipulation functions just to name a few. Table 1 : Lists some of the common Built in Functions in
the Mathematical category.

Table 1

Function Name Description

Abs Returns the absolute value of a number.


Cos Returns the cosine of the specified angle.
Cosh Returns the hyperbolic cosine of the specified angle.
Exp Returns e (the base of natural logarithms) raised to the specified power.
Fix Returns the integer portion of a number.
Format Takes a numeric expression and returns it as a formatted string.
Int Returns the integer portion of a number.
Log Returns the natural (base e) logarithm of a specified number or the logarithm of a specified
number in a specified base.
Rnd Generates a random number (integer value)
Round Returns a Decimal or Double value rounded to the nearest integral value or to a specified
number of fractional digits.
Sign Returns an Integer value indicating the sign of a number.
Sin Returns the sine of the specified angle.
Sqr Returns the square root of a specified number.
Tan Returns the tangent of the specified angle.
Val Accepts a string as input and returns the numbers found in that string.

1 Dim a, b as integer Logical Functions

a=81 Table 2. lists some of the common Built in Functions in


the Logical category.
debug.print sqr(a)

This will display the square root of 81 ie. 9


115

Copyright Free under CC BY Licence


Table 2

Function Name Description

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.

Examples: If IsDate(N) = True Then


MsgBox "correct"
1 Sub Button1_Click()
Else
N = TextBox1.Text
MsgBox "Insert only dates"
If IsNumeric(N) = True Then
End If
MsgBox "correct"
End Sub
Else
This checks if the data entered in the textbox is a valid
MsgBox "Insert only numbers"
date or not.
End If
Date / Time Functions
This checks if the data entered in the textbox is a
number or not. Table 3. lists some of the common Built in Functions in
the Date / Time category.
2 Sub Button1_Click()
N = TextBox1.Text

Table 3

Function Return Value

DATE Returns the current system date.


DATEADD Returns a date after which a certain time/date interval has been added.
DATEDIFF Returns the difference between two date values, based on the interval specified.
DATEPART Returns a specified part of a given date.
DATESERIAL Returns a date given a year, month, and day value.
DATEVALUE Returns the serial number of a date.
DAY Returns the day of the month (a number from 1 to 31) given a date value.
FORMAT Dates Takes a date expression and returns it as a formatted string.
HOUR Returns the hour of a time value (from 0 to 23).
MINUTE Returns the minute of a time value (from 0 to 59).
MONTH Returns the month (a number from 1 to 12) given a date value.
MONTHNAME Returns a string representing the month given a number from 1 to 12.
NOW Returns the current system date and time.
TIMESERIAL Returns a time given an hour, minute, and second value.
TIMEVALUE Returns the serial number of a time.
WEEKDAY Returns a number representing the day of the week, given a date value.
WEEKDAYNAME Returns a string representing the day of the week given a number from 1 to 7.
YEAR Returns the year portion of the date argument.

116 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.113

Copyright Free under CC BY Licence


Examples 2 Format Date

1 DateDiff() Function Syntax


Syntax for the DateDiff function is :
The syntax for the Microsoft Excel FORMAT function is:
DateDiff (interval, date1, date2, [firstdayofweek],
[firstweekofyear]) Format ( expression, [ format, [ firstdayofweek,
[firstweekofyear] ] ] )
Parameters or Arguments
Parameters or Arguments
Interval is the interval of time to use to calculate the
difference between date1 and date2. Below is a list of
Expression is the value to format.
valid interval values as in Table 4

Table 4 Format is optional. It is the format to apply to the


expression. You can either define your own format or use
Interval Explanation one of the named formats that Excel has predefined such
as shown in Table 5.
yyyy Year
Table 5
q Quarter
m Month Format Explanation

y Day of year General Date Displays date based on your


d Day system settings

w Weekday Long Date Displays date based on your


system's long date setting
ww Week
Medium Date Displays date based on your
h Hour system's medium date setting
n Minute Short Date Displays date based on your
s Second system's short date setting
Long Time Displays time based on your
Date1 and Date2 are the two dates to calculate the system's long time setting
difference between.
Medium Time Displays time based on your
first day of week is optional. It is a constant that specifies system's medium time setting
the first day of the week. If this parameter is omitted, Excel Short Time Displays time based on your
assumes that Sunday is the first day of the week. system's short time setting

first week of year is optional. It is a constant that specifies


First day of week is optional. It is a value that specifies
the first week of the year. If this parameter is omitted,
the first day of the week. If this parameter is omitted, the
Excel assumes that the week containing Jan 1st is the
FORMAT function assumes that Sunday is the first day of
first week of the year.
the week. This parameter can be one of the following values
as shown in Table 6.
Sub test()
First week of year is optional. It is a value that specifies
Debug.PrintDateDiff("yyyy", "1/12/1999", "31/1/2000")
the first week of the year. If this parameter is omitted, the
FORMAT function assumes that the week that contains
Debug.PrintDateDiff("q", "1/12/1999", "31/1/2000")
January 1 is the first week of the year. This parameter can
Debug.PrintDateDiff("m", "1/12/1999", "31/1/2000") be one of the following values as shown in Table 7.

End Sub Sub test()

The result will be Debug.Print Format(#1/1/1990#, "Short Date")

1 Debug.Print Format(#1/1/1990#, "Long Date")

4 Debug.Print Format(#1/1/1990#, "yyyy/mm/dd")

12 End Sub

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.113 117

Copyright Free under CC BY Licence


Table 6 Table 7

Constant Value Explanation Constant Value Explanation

vbUseSystem 0 Uses the NLS API setting vbUseSystem 0 Uses the NLS API setting

VbSunday 1 Sunday (default, if vbFirstJan1 1 The week that contains


parameter is omitted) January 1

vbMonday 2 Monday vbFirstFourDays 2 The first week that has at


least 4 days in the year
vbTuesday 3 Tuesday
vbFirstFullWeek 3 The first full week of the
vbWednesday 4 Wednesday year

vbThursday 5 Thursday Monday, January 01, 1990


vbFriday 6 Friday 1990/01/01
vbSaturday 7 Saturday Data Type Conversion Functions

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

Function Return Type Range for expression argument

CBool Boolean Any valid string or numeric expression.


CByte Byte 0 to 255.
CCur Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
CDate Date Any valid date expression.
CDbl Double -1.79769313486231E308 to -4.94065645841247E-324 for negative values;
4.94065645841247E- 324 to 1.79769313486232E308 for positive values.
CDec Decimal +/-79,228,162,514,264,337,593,543,950,335 for zero-scaled numbers,
that is, numbers with no decimal places. For numbers with 28 decimal
places, the range is +/-7.9228162514264337593543950335. The smallest
possible non-zero number is 0.0000000000000000000000000001.
CInt Integer -32,768 to 32,767; fractions are rounded.
CLng Long -2,147,483,648 to 2,147,483,647; fractions are rounded.
CSng Single -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45
to 3.402823E38 for positive values.
CStr String Returns for CStr depend on the expression argument.
CVar Variant Same range as Double for numerics. Same range as String for non-numerics.

Example Debug.PrintCDate(b)
CDate function c = "1:23:45 PM"
Sub test() Debug.PrintCDate(c)
Dim lNum As Long End Sub
Dim a As String This will display
a = 12345 10/18/1933
Debug.PrintCDate(a) 1/1/1990
b = "January 1, 1990" 1:23:45 PM

118 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.113

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.114 & 2.2.115
COPA - Programming with VBA

User defined functions in VBA


Objectives: At the end of this lesson you shall be able to
• create user defined functions
• describe passing values to functions byval and byref
• describe using arrays with functions
• describe the scope of variables
• describe the access specifiers public and private.

Introduction b = 20

In Excel Visual Basic too, like in most programming Debug.Print "area Is " & l * b
languages, a set of commands to perform a specific task
is placed into a procedure, which can be a function or a End Function
subroutine. The main difference between a VBA function
and a VBA subroutine is that a function (generally) returns When executed from the immediate window this function
a result, whereas a subroutine does not. displays the area.

Therefore, if you wish to perform a task that returns a Alternately this function can be called by another
result (ex. summing of a group of numbers), you will subroutine, for ex.
generally use a function, but if you just need a set of actions
to be carried out (ex. formatting a set of cells), you might Sub test_fn()
choose to use a subroutine.
Call area
User Defined Functions
End Sub
One of the most power features of Excel VBA is that you
can create your own functions or UDFs. A UDF (User Returning a value from the procedures
Defined Function) is simply a function that you create
yourself with VBA for your own defined tasks. UDFs are In the example given below, the area() function calculates
often called "Custom Functions". A UDF can remain in a l*b.
code module attached to a workbook, in which case it will
always be available when that workbook is open. The subroutine that calls this function is returned this value.
Alternatively you can create your own add-in containing
one or more functions that you can install into Excel. Here Sub test_fn()
the user-defined functions can be entered into any cell or
Debug.Print "The function has returned the value " & area
on the formula bar of the spreadsheet just like entering
the built-in formulas of the MS Excel spreadsheet.
End Sub
Custom functions, like macros, use the Visual Basic for
Function area()
Applications (VBA) programming language. They differ from
macros in two significant ways. First, they use function
Dim l, b, A
procedures instead of sub procedures. They start with a
Function statement instead of a Sub statement and end l = 10
with End Function instead of End Sub. Second, they
perform calculations instead of taking actions. Certain b = 20
kinds of statements (such as statements that select and
format ranges) are generally excluded from custom area = l * b
functions.
End Function
A simple function may look like this:
The result will be:The function has returned the value 200
Function area()
Passing Arguments to functions
Dim l, b
We can pass the arguments in two different ways:
l = 10

119

Copyright Free under CC BY Licence


1 By Value (ByVal): We pass the copy of the actual value Function Modify(ByRef A As Integer)
to the arguments
A=A*2
2 By Reference (ByRef): We pass the reference to the
arguments
Modify = A
By Ref is the default method of passing argument type in
VBA. This means, if you are not specifying any type of End Function
the argument it will consider it as ByRef type. However, it
is always a good practice to specify the ByRef even if it is The result will be:
not mandatory.
The function has returned the value 20
The following example shows the method of passing
variables to a function byVal. A is now 20

Sub test_fn() Calling a User Defined Function from Worksheet:

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

The following example shows the method of passing Next i


variables to a function byRef.
'call the function example 1 with arrIntegers as an input
Sub Test() parameter

Dim A As Integer Call fn1(arr)

A = 10 For i = 1 To 10

Debug.Print "The function has returned the value " & Debug.Print arr(i); Spc(2);
Modify(A)
Next i
Debug.Print "A is now " & A
End Sub
End Sub

120 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.114 & 2.2.115

Copyright Free under CC BY Licence


'prints the values in arrIntegers to column A For Example the following subroutine has been created in
Module1 code.
Sub fn1(ByRef arr() As Integer)
Sub disp()
Dim i As Integer
Dim s As string
For i = LBound(arr) To UBound(arr)
s="hello"
arr (i) = arr (i) * 2
MsgBox s
Cells (i,1) = arr (i)
End Sub
Next i
Run the subroutine "disp" in Module1 and it will display
End Sub
the message "Hello" in the message box.
Scope of variables
Now the following subroutine has been created in Sheet1
The term Scope is used to describe how a variable may code to call the disp() subroutine from Module1.
be accessed. Depending on where and how a variable is
declared, it may be accessible only to a single procedure, Sub Button1_Click()
to all procedures within a module, and so on up the
hierarchy of a project or group of related projects. The disp
term visibilty is also is sometimes used to describe scope.
End Sub
There are four levels of Scope:
This will generate an error since the subroutine disp() and
• Procedure-Level Scope
the variable s are local to Module1 and cannot be accessed
• Module-Level Scope from elsewhere.

• Project-Level Scope Static:

• Global-Level Scope A local variable declared with the Static statement remains
in existence the entire time Visual Basic is running. The
Fig 1 shows the various scopes and their levels.
variable is reset when any of the following occur:
Fig 1
• The macro generates an untrapped run-time error.
Global scope • Visual Basic is halted.
Project scope • You quit Microsoft Excel.
Module scope • You change the module.

Procedure scope
For example, in the FindTotal example, the Accumulate
variable retains its value every time it is executed. The
first time the module is run, if you enter the number 2, the
message box will display the value "2." The next time the
module is run, if the value 3 is entered, the message box
will display the running total value to be 5.

Sub FindTotal()
Procedure (local) scope
Static Total
A local variable with procedure scope is recognized only
Dim n as integer
within the procedure in which it is declared. A local variable
can be declared with a Dim or Static statement.
n =InputBox("Enter a number: ")
When a local variable is declared with the Dim statement,
Total = Total + n
the variable remains in existence only as long as the
procedure in which it is declared is running. Usually, when
MsgBox "The total is " &n
the procedure is finished running, the values of the
procedure's local variables are not preserved, and the
End Sub
memory allocated to those variables is released. The next
time the procedure is executed, all of its local variables
are reinitialized.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.114 & 2.2.115 121

Copyright Free under CC BY Licence


Module scope End Sub

A variable that is recognized among all of the procedures Sub Test4()


on a module sheet is called a "module-level" variable. A
module-level variable is available to all of the procedures MsgBox A
in that module, but it is not available to procedures in
other modules. A module-level variable remains in existence MsgBox B
while Visual Basic is running until the module in which it
is declared is edited. Module-level variables can be MsgBox C
declared with a Dim or Private statement at the top of the
module above the first procedure definition. ' The message box is blank since C is a local variable.

At the module level, there is no difference between Dim End Sub


and Private. Note that module-level variables cannot be
declared within a procedure. Project Scope

Note If you use Private instead of Dim for module-level Project scope variables are those declared using the Public
variables, your code may be easier to read (that is, if you keyword. These variables are accessible from any
use Dim for local variables only, and Private for module- procedure in any module in the project. In Excel, a Project
level variables, the scope of a particular variable will be is all of the code modules, userforms, class modules, and
more clear). object modules (e.g. ThisWorkbook and Sheet1) that are
contained within a workbook.
In the following example, two variables, A and B, are
declared at the module level. These two variables are In order to make a variable accessible from anywhere in
available to any of the procedures on the module sheet. the project, you must use the Public keyword in the
The third variable, C, which is declared in the Example3 declaration of the variable. However, this makes the variable
macro, is a local variable and is only available to that accessible to any other project that reference the project
procedure. containing the variable. If you want a variable to be
accessible from anywhere within the project, but not
Note that in Test4, when the macro tries to use the variable accessible from another project, you need to use Option
C, the message box is empty. The message box is empty Private Module as the first line in the module (above and
because C is a local variable and is not available to Test4, outside of any variable declaration or procedure). This option
whereas variables A and B are. makes everything in the module accessible only from within
the project. The project variables that should not be
Dim A As Integer ' Module-level variable. accessible to other projects should be declared in a module
that has the Option Private Module directive. Variables
Private B As Integer ' Module-level variable. that should be accessible to other project should be
declared in a different module that does not use the Option
Sub Test1() Private Module directive. In both cases, however, you need
to use the Public keyword.
A = 10
Global Scope
B = A * 10
Global scope variables are those that are accessible from
End Sub anywhere in the project that declares them as well as any
other project that references the first project. To declare a
Sub Test2() variable with global scope, you need to declare it using
the Public keyword in a module that does not use the
MsgBox "The value of A is " & A Option Private Module directive. In order to access variables
in another project, you can simply use the variable's name.
MsgBox "The value of B is " & B If, however, it is possible that the calling project also has a
variable by the same name, you need to prefix the variable
End Sub name with the project name. For example, if Project1
declares a global variable named x, and Project2 references
Sub Test3() Project1, code that is in Project2 can access x with either
of the following lines of code:
Dim C As Integer ' Local variable.
x = 78
C=A+B
Project1.x = 78
MsgBox "The value of C is " & C

122 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.114 & 2.2.115

Copyright Free under CC BY Licence


If both Project1 and Project2 have variables with at least of a subroutine (usually at the very top of your module).
project scope, you need to include the project name with You can use this type of variable when you have one
the variable. For clarity and maintainability, you should subroutine generating a value and you want to pass that
always include the project name when accessing a variable value on to another subroutine in the same module.
that is declared in another project. Even if this is not
necessary, it makes the code more readable and Dim[variable] is used to state the scope inside of a
maintainable. subroutine (you cannot use Private in its place). Dim can
be used either inside a subroutine or outside a subroutine
There is no way to give some variables project, but not (using it outside a subroutine would be the same as using
global, scope and give others in the same module global Private).
scope. Project versus global scope is handled only at the
module level, not at the variable level. Example of Public, Private Variables and Procedures.

The Access Specifiers Module 1 code

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

1 Private Call Third_Sub()

2 Public End Sub


A Public procedure is accessible to all code inside the
module and all code outside the module, essentially Private Sub Second_Sub()
making it global. A VBA Private Sub can only be called
from anywhere in the Module in which it resides. A Public MsgBox "Gone through First, Second and Third
Sub in the objects, ThisWorkbook, ThisDocument, Sheet1, Subroutines !"
etc. cannot be called from anywhere in a project. However,
End Sub
if you declare a Module level variable with the Public
Keyword it can be used anywhere in the project and retains
Module 2 code
its value.
Sub Third_Sub()
If you exclude the key word private in your declaration then
by default the procedure is public. So Sub MySub()
Debug.Print x
and Public Sub MySub() are exactly the same thing.
Debug.Print y
Public [variable] means that the variable can be accessed
or used by subroutines in outside modules. These variables Call Second_Sub()
must be declared outside of a subroutine (usually at the
very top of your module). You can use this type of variable End Sub
when you have one subroutine generating a value and you
want to pass that value on to another subroutine stored in The two variables x and y that are declared outside a
a separate module. subroutine. This means that their values can carry over
into other macros. The variable x has a private scope so
A Private procedure is only available to the current module. only subroutines in the same module can access its value.
It cannot be accessed from any other modules, or from the The variable y has a public scope, meaning that
Excel workbook.Private Sub sets the scope so that subroutines inside and outside its module can access its
subroutines from outside modules cannot call that particular value.
subroutine. This means that a sub in Module 1 could not
use the Call method to initiate a Private Sub in Module 2. The First_Sub() assigns values to x and y and then initiates
the Third_Sub().
Private [variable] means that the variable cannot be
accessed or used by subroutines in other modules. In Third_Sub() can be called even though it is not in the same
order to be used, these variables must be declared outside module because it is a Public Sub.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.114 & 2.2.115 123

Copyright Free under CC BY Licence


The Third_Sub() has been designed to display the values trying to call a private subroutine " Second_Sub" from here.
of x and y in the immediate window. When you try to print The following changes can be done to avoid this:
variable x it outputs nothing. This is because x does not
exist in Module 2. Therefore, a new variable x is created 1 We could remove the word "Private" from
in Module 2 and since we did not give this new x a value, Display_Message
nothing is printed for the statement Debug.Print x 2 We could replace "Private" with "Public" in
Second_Sub()
When we print the value of the variable y, 12 is displayed
in the Immediate Window. This is because Module 2 3 We can use the Application level and instead of using
subroutines have access to the public variables declared Call we could write Application.Run "Second_Sub " (this
in Module 1.But the statement "Call Second_Sub()" in the method serves as an override in case we wanted to
Third_Sub() will result in an error. This is because we are keep Second_Sub private for subroutines outside the
module.)

124 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.114 & 2.2.115

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.116
COPA - Programming with VBA

Create and Edit Macros


Objective: At the end of this lesson you shall be able t0
• explain about Macros in VBA.

Macros offer a powerful and flexible way to extend the 4 Absolute versus Relative Macros
features of Excel. They allow the automation of repetitive
An “Absolute” macro will always affect the same cells
tasks such as printing, formatting, configuring, or
each time whereas a “Relative” macro will affect those
otherwise manipulating data in Excel. In its’ simplest form,
cells relative to where the cursor is positioned when
a macro is a recording of your keystrokes. While macros
invoke the macro. It is crucial that understand the
represent one of the stronger features found in Excel, they
difference.
are rather easy to create and use. There are six major
points that I like to make about macros as follows.
5 Editing Macros
1 Record, Use Excel, Stop Recording Once created, you can view and/or edit your macro
using the View Macros option. This will open the macro
To create a macro, simply turn on the macro recorder, subroutine in a Visual basic programming window and
use Excel as you normally do, then turn off the recorder. provide you with a plethora of VB tools.
Presto – you have created a macro. While the
process is simple from the user’s point of view, 6 Advanced Visual Basic Programming
underneath the covers Excel creates a Visual Basic
subroutine using sophisticated Visual Basic For the truly ambitious CPA, in the Visual Basic
programming commands. Programming window, you have the necessary tools
you need to build very sophisticated macros with dialog
2 Macro Location boxes, drop down menu options, check boxes, radio
buttons – the whole works. To see all of this power,
Macros can be stored in either of two locations, turn on the “Developer Tab” in “Excel Options”.
as follows: Presented below are more detailed comments and
stepbystep instructions for creating and invoking
The workbook you are using, or the Personal Macro
macros, followed by some example macros.
Workbook (which by default is hidden from view) If
the macro applies to all workbooks, then store it
Page Setup Macro Start recording a new macro called
in the Personal Macro Workbook so it will always be
page setup. Select all of the worksheets and then choose
available in all of the Excel workbooks; otherwise store
Page Setup and customize the header and footers to
it in the current workbook. A macro stored in the current
include page numbers, date and time stamps, file locations,
workbook will embedded and included in the
tab names, etc. Assign the macro to an Icon onthe toolbar
workbook, even if you email the workbook to
or Quick Access Bar and insetting headers and footers
another user.
will be a breeze for the rest of your life.
3 Assign the Macro to an Icon, Text or a Button
Print Macros Do you have a template that print frequently
To make it easy to run your macro, you should assign from? If so, insert several macro buttons to print each
it to a toolbar icon so it will always be available no report, a group of reports, and even multiple reports and
matter which workbooks you have open. If the macro reporting will be snap in the future.
applies only to the current workbook, then assign it to
Text or a macro Button so it will be quickly available in Delete Data Macro create a macro that visits each cell
the current workbook. and erases that data, resetting the worksheet for use in a
new set of criteria. Assign the macro to a macro
button and will never again have old assumptions
mixed in with your newer template

125

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.117
COPA - Programming with VBA

User forms and control in Excel VBA


Objectives: At the end of this lesson you shall be able to
• define forms and controls in VBA
• describe the types of excel forms
• describe the properties, methods and events of forms.

Introduction to Forms and Controls Creating VBA Forms

A form is a document designed with a standard structure A VBA form can be created from the code window. To
and format that makes it easier to enter, organize, and create a Form in VBA,click on Insert menu in the code
edit information. Forms contain labels, textboxes, drop window and then click 'UserForm'. A UserForm1 appears
down boxes and command buttons too. in the project window.

By using forms and the many controls and objects that When you create or add a form, a module is also
you can add to them, you can significantly enhance data automatically created for it. To access the module
entry on your worksheets and improve the way your associated with a form, you can right-click the form and
worksheets are displayed. click View Code.Double Clicking on the Form or pressing
F7 will also open the Code window. Using Shift F7 will
Types of Excel forms again switch back to the Design Window.

There are several types of forms that you can create in The design time properties of the Form can be set by right
Excel: data forms, worksheets that contain Form and clicking on the form and selecting 'Properties'. The same
ActiveX controls, and VBA UserForms. can be achieved by Clicking "F4" or the properties button
on the Form.Controls can be placed on the form from the
Data form ToolBox as per requirement.

A data form provides a convenient way to enter or display In addition, Controls can be added on the Form
one complete row of information in a range or table without programmatically / at run time using the "Add" method.
scrolling horizontally. You may find that using a data form Similarly the controls can be removed from the form at run
can make data entry easier than moving from column to time / programmatically using the "Remove" method. As
column when you have more columns of data than can be an example to add a checkbox control, we can write
viewed on the screen. Excel can automatically generate a
built-in data form for your range or table. Set cb1 = Controls.Add("Forms.CheckBox.1")

Worksheet with Form and ActiveX controls Some of the events and methods connected with the form
object are:
A worksheet can be considered to be a form that enables
you to enter and view data on the grid. Events, Activate, Deactivate, Add Control, Remove Control,
Click, DblClick, Initialize, KeyPress, Resize, Scroll,
For added flexibility, you can add controls and other drawing Terminate, Zoom etc.
objects to the worksheet, and combine and coordinate
them with worksheet cells. For example, you can use a Methods Copy, Paste, Hide, Move, Print Form, Repaint,
list box control to make it easier for a user to select from Scroll, Show etc .
a list of items. Or, you can use a spin button control to
make it easier for a user to enter a number. The code needed to perform various operations on Forms
is given in Table 1.
You can display or view controls and objects alongside
associated text that is independent of row and column A sample Form for data entry of students' details, marks
boundaries without changing the layout of a grid or table and results is shown in Fig. 1.
of data on your worksheet. Many of these controls can
also be linked to cells on the worksheet and do not require Necessary code can be attached to the Command Buttons
VBA code to make them work. For example, you might and other controls shown. After the user enters the data,
have a check box that you want to move together with its the total is calculated and the result is displayed. The
underlying cell when the range is sorted. However, if you records can then be stored appropriately.
have a list box that you want to keep in a specific location
at all times, you probably do not want it to move together
with its underlying cell.

126

Copyright Free under CC BY Licence


Table 1

Userform VBA Code Action


Application

To Display a UserForm1.Show Displays the UserForm with name UserForm1. This code should be
UserForm inserted in a Standard VBA Module and not in the Code Module of the
UserForm. You can create a button in a worksheet, then right click to
assign macro to this button, and select the macro which shows the
UserForm.
Load a UserForm Load UserForm1 Load statement is useful in case of a complex UserForm that you
into memory but do want to load into memory so that it displays quickly on using the
not display Show method, which otherwise might take a longer time to appear.

Remove a User Unload UserForm1 Note: The Hide method (UserForm1.Hide) does not unload the
Form from memory UserForm from memory. To unload the UserForm from memory, the
/ Close UserForm Unload method should be used.
Unload Me Use the Me keyword in a procedure in the Code Module of the UserForm.

Hide a UserForm UserForm1.Hide Using the Hide method will temporarily hide the UserForm, but will not
close it and it will remain loaded in memory.
Print a UserForm UserForm1.PrintForm The PrintForm method sends the UserForm directly for printing.
Display UserForm UserForm1.Show False If the UserForm is displayed as Modeless, user can continue working
as Modeless in Excel while the UserForm continues to be shown. Omitting the
Boolean argument (False or 0) will display the UserForm as Modal, in
which case user cannot simultaneously work in Excel. By default
UserForm is displayed as Modal.
Close a UserForm Unload UserForm1 The Unload method closes the specified UserForm.
Unload Me The Unload method closes the UserForm within whose Code Module
it resides.
End Use the End statement in the "Close" CommandButton to close the
form. The "End" statement unloads all forms.
Specify UserForm UserForm1.Caption Caption is the text which describes and identifies a UserForm and will
Caption = "Bio Data" display in the header of the Userform.
Set UserForm UserForm1.Height
size = 250 Set Height of the UserForm, in points.
UserForm1.Width
= 350 Set Width of the UserForm, in points.
Set UserForm Position:

Left & Top UserForm1.Left = 30 Distance set is between the form and the Left or Top edge of the
properties UserForm1.Top = 50 window that contains it, in pixels.

Move method UserForm1.Move Move method includes two arguments which are required - the Left
200, 50 distance and the Top distance, in that order.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.117 127

Copyright Free under CC BY Licence


Necessary code can be attached to the Command Buttons
and other controls shown. After the user enters the data,
the total is calculated and the result is displayed. The
records can then be stored appropriately.

Fig 1

128 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.117

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.118
COPA - Programming with VBA

Methods and Events in VBA


Objectives: At the end of this lesson you shall be able to
• explain VBA methods and events.

Methods and Events


Fig 2

Methods

A method is an action you perform with an object. A method


can change an object's properties or make the object do
something.

For example painting is a Method, building a new room is


a method in building a new house.

Similarly, if you want to select a range, you need Select


method. If you want to copy a range from one worksheet to
another worksheet you need Copy method to do it.

The following example Copies the data from Range A1 to


B5.

Enter the following code in the Module1 as shown in Fig 1


Events
Sub sbExampleRangeMethods()
Range("A1").Select An Event is an action initiated either by user action or by
other VBA code. An Event Procedure is a Sub procedure
Selection.Copy
that you write, according to the specification of the event,
Range("B5").Select that is called automatically by Excel when an event
occurs. For example, a Worksheet object has an event
ActiveSheet.Paste
named Change. If you have properly programmed the
End Sub event procedure for the Change event, Excel will
automatically call that procedure, always named
Fig 1 Worksheet_Change and always in the code module of the
worksheet, whenever the value of any cell on the worksheet
is changed by user input or by other VBA code (but not if
the change in value is a result of a formula calculation).
You can write code in the Worksheet_Change event
procedure to take some action depending on which cell
was changed or based upon the newly changed value.

Enter the following code in the Worksheet_Change event


as shown in Fig 3.

Private Sub Worksheet_Change(ByVal Target


As Range)
MsgBox "Changed"
If the above code is executed the content of cell A1 is
copied to Cell B5 as shown in the Fig 2. End Sub

129

Copyright Free under CC BY Licence


Fig 3 When we change content of any Cell the following message
will be displayed as shown in Fig 4.
Fig 4

130 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.118

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.119
COPA - Programming with VBA

Debugging Techniques in VBA


Objectives: At the end of this lesson you shall be able to
• explain about VBA debugging
• explain how to set and clear the Breakpoints
• describe use of immediate window
• explain about watch window.

VBA Debugging Setting a Breakpoint

In Excel 2010, VBA’s debugging environment allows the First, you need to open the VBA environment. The quickest
programmer to momentarily suspend the execution of VBA way to do this is by pressing Alt+F11 while the Excel
code so that the following debug tasks can be done: database file is open.
To set a breakpoint, find the line of code where to suspend
1 Check the value of a variable in its current state.
your program. Left-click in the grey bar to the left of the
2 Enter VBA code in the Immediate window to view the code. A red dot should appear and the line of code should
results. be highlighted in red.
3 Execute each line of code one at a time.
Clear Breakpoint in VBA
4 Continue execution of the code.
5 Halt execution of the code. A breakpoint in VBA is indicated by a red dot with a line
of code highlighted in red.
These are just some of the tasks that you might perform To clear a breakpoint in Excel 2010, left-click on the red
in VBA’s debugging environment. (Fig 1) dot next to the line of code that has the breakpoint.
Fig 1
(Fig 2)

Fig 2

Breakpoint in VBA

In Excel 2010, a breakpoint is a selected line of code that In this example, we want to clear the breakpoint at the
once reached, the program will momentarily become
following line of code:
suspended. Once suspended, and to use VBA’s debugging
environment to view the status of program, step through
LChar = Mid(pValue, LPos, 1) (Fig 3)
each successive line of code, continue execution of the
code, or halt execution of the code.
Now, the breakpoint is cleared and the line of code should
And create as many breakpoints in the code as you want. look normal again. (Fig 4)
Breakpoints are particularly useful when suspend the
program where you suspect a problem/bug exists.

131

Copyright Free under CC BY Licence


Fig 3 Fig 5

Debug Mode
Fig 4
Now that we know how to set and clear breakpoints in
Excel 2010, let’s take a closer look at the debug mode
in VBA.

In our example, we’ve set our breakpoint and entered our


AlphaNumeric function as a formula in a cell. This will
cause the VBA code to execute. (Fig 6)
Fig 6

In this example, we’ve created a breakpoint at the following


line of code:
When the breakpoint is reached, Excel will display the
LChar = Mid(pValue, LPos, 1) Microsoft Visual Basic window and highlight the line (in
yellow) where the code has been suspended. (Fig 7)
Now, the breakpoint is cleared and the line of code should
look normal again Fig 7

Clearing all Breakpoints

If user use as many breakpoints as you want in Excel


2010, and can save time by clearing all breakpoints in the
VBA code at once.

To clear all breakpoints in the program, select “Clear All


Breakpoints” under the Debug menu. (Fig 5)

This will remove all breakpoints from the VBA code, so


that you don’t have to individually remove each breakpoint,
one by one.

132 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.119

Copyright Free under CC BY Licence


Now we are in debug mode in our Excel spreadsheet. In this example, we typed print pValue in the Immediate
Now we can do any of the following: window and pressed ENTER.
Print pValue
1 Check the value of a variable in its current state.
2 Enter VBA code in the Immediate window to view the The Immediate window displayed the result in the next
results. line. In this case, the print pValue command returned 123
3 Execute each line of code one at a time. Main St.

4 Continue execution of the code. You can also type more complicated expressions in the
Immediate window. (Remember to press ENTER.) For
5 Halt execution of the code.
example: (Fig 10)

Using the Immediate Window Fig 10

In Excel 2010, the Immediate window can be used to debug


your program by allowing you to enter and run VBA code
in the context of the suspended program. (Fig 8)

Fig 8

In this example, we typed print Mid(pValue, LPos, 1) in


the Immediate window and pressed ENTER.
print Mid(pValue, LPos, 1)

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.

To add a Watch expression, select Add Watch under the


Debug menu. (Fig 11)

When the Add Watch window appears, enter the


expression to watch and click the OK button when you
are done. (Fig 12)

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.119 133

Copyright Free under CC BY Licence


Fig 11 Fig 12

Next, we’ve selected AlphaNumeric as the Procedure


In this example, we’ve entered the following watch and Module1 as the Module when setting up the Context
expression in the Expression field: for the watched expression.
Mid(pValue, LPos, 1) Finally, we’ve selected Watch Expression as the Watch
Type but there are 3 options to choose from:

Watch Type Description

Watch Expression To display the value of the watched expression in its current state

Break When Value Is True To stop the execution of the code when the value of the watched expression is
True

Break When Value Changes To stop the execution of the code when the value of the watched expression
changes

When return to the VBA window, the Watch Window will As you can see, the expression Mid(pValue, LPos, 1)
automatically appear if it was previously hidden. Within now appears in the Watch Window with a value of “1”.
the Watch Window, all of the watched expressions should Adding a watch is a great way to keep track of variables or
be listed including the one that we just added. (Fig 13) expressions of interest when debugging the VBA code.

Fig 13

134 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.119

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.2.120
COPA - Programming with VBA

Object Oriented Programming concepts, Concepts of classes, Objects,


properties and Methods
Objectives: At the end of this lesson you shall be able to
• explain Class and objects and its features
• explain VBA Class modules Versus VBA normal modules
• list out parts of a class module and its properties
• explain class module events.

Introduction Disadvantages of Using Objects

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.

The idea is that the code of each object is self-


contained. It is completely independent of any other
code in our application.

Advantages of Using Objects

Treating parts of our code as blocks provide us with a lot


of advantages

1 It allows us to build an application one block at a time.


2 It is much easier to test individual parts of an
application.
3 Updating code won’t cause problems in other parts of
the application.
Adding a Class Module
4 It is easy to add objects between applications.
Our new class is called Class1. We can change the name
in the Properties window.

135

Copyright Free under CC BY Licence


Let’s change the name of the class module to Dim oItem AsNew Class1
clsCustomer. Then we will add a variable to the class
module like this Dim oCustomer1 AsNewclsCustomer

Dim coll AsNew Collection


Public Name AsString (Fig 2)
Note: We don’t use New with items such as
Fig 2 Workbooks and Worksheets. See When New
is not required for more information.

VBA Class Modules Versus VBA Normal Modules

Writing code in a class module is almost the same as


writing code in a normal module. We can use the same
code we use in normal modules. It’s how this code is
used which is very different.

Let’s look at the two main differences between the class


and normal module. These often cause confusion among
new users.
Difference 1 – How the modules are used

If want to use a sub/function etc. from a class module


must create the object first.

For example, imagine we have two identical


We can use now use this class module in any
PrintCustomer subs. One is in a class module and one
module(standard or class) in our workbook. For example
is in a normal module…
‘ Create the object from the class module
‘ CLASS MODULE CODE - clsCustomer
Dim oCustomer AsNew clsCustomer
Public Sub PrintCustomer()
‘ Set the customer name
Debug.Print “Sample Output”
oCustomer.Name = “John”
End Sub
‘ Print the name to the Immediate Window(Ctrl + G)
‘ NORMAL MODULE CODE
Debug.Print oCustomer.Name

Public Sub PrintCustomer()


Class Module versus Objects

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 class module can be thought of as the design. Sub UseCustomer()

The object can be thought of as the item that is created Dim oCust AsNew clsCustomer
from the design.
oCust.PrintCustomer
The New keyword in VBA is what we use to create an
object from a class module. For example EndSub

‘ Creating objects using new To use Print Customer from the normal module you can
call it directly

136 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120

Copyright Free under CC BY Licence


‘ Other Module Private dBalance As Double

Sub Use Customer() ‘ Properties

Print Customer Property Get Balance () AsDouble

End Sub Balance = dBalance

Difference 2 – Number of copies EndProperty

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

For example, imagine we create a variable Student Name End Property


in both a class and normal module..
‘ NORMAL MODULE ‘ Event - triggered when class created

Public StudentName As String


Private Sub Class_Initialize()
‘ CLASS MODULE
dBalance = 100
Public Studen tName As String
EndSub
For the normal module variable there will only be one copy
of this variable in our application. ‘ Methods
StudentName = “Ram”
Public Sub Withdraw (dAmountAs Double)
For the class module a new copy of the variable Student
dBalance = dBalance - dAmount
Name is created each time a new object is created.
End Sub
Dim student1 As New clsStudent
Public Sub Deposit (dAmountAs Double)
Dim student 2 As New clsStudent
dBalance = dBalance + dAmount
student1.Student Name = “Bill”
EndSub
student2.Student Name = “Ted”
Now that we have seen examples, let’s look at each of
When fully understand VBA class modules, these these in turn.
differences will seem obvious.
Class Module Methods
The Parts of a Class Module
Methods refer to the procedures of the class. In VBA
There are four different items in a class module. These are procedures are subs and functions. Like member variables
1 Methods – functions/subs. they can be Public or Private.
2 Member variables – variables.
Let’s look at an example
3 Properties– types of functions/subs that behave like
variables. ‘ CLASS MODULE CODE

4 Events – subs that are triggered by an event. ‘ Class name: clsSimple

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

‘ Member variable EndSub

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120 137

Copyright Free under CC BY Licence


Public Function Calculate (dAmountAs Double) As In the above example we cannot access Balance because
Double it is declared as Private. We can only use a Private
variable within the class module. We can use in a function/
Calculate = dAmount - GetDeduction sub in the class module e.g.

End Function ‘ CLASS MODULE CODE

‘ 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.

dTotal = oSimple.Calculate(22.44) Class Module Properties

Debug.Print dTotal 1 Get – returns an object or value from the class

EndSub 2 Let – sets a value in the class


3 Set – sets an object in the class
Class Module Member Variables
Format of VBA Property
The member variable is very similar to the normal variable
we use in VBA. The difference is we use Public or Private The normal format for the properties are as follows:
instead of Dim.
Public Property Get () AsType
‘ CLASS MODULE CODE End Property

Private Balance AsDouble Public Property Let (varnameAsType )

Public AccountID As String End Property

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

‘ Error - Balance is private ‘ Use array to store countries

oAccount.Balance = 678.90 Public arrCountries As Variant

138 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120

Copyright Free under CC BY Licence


‘ Set size of array when class is initialized Count = collCountries.Count
Private Sub Class_Initialize()
End Function
ReDim arrCountries (1 To 1000)
The caller is oblivious to how the countries are stored. All
the caller needs to know is that the Count function will
End Sub
return the number of countries.
When the user wants to get the number of countries in the
As we have just seen, a sub or function provides a solution
list they could do this
to the above problems. However, using a Property can
‘ NORMAL MODULE CODE provide a more elegant solution.

Dim oCountry As New clsCountry Using a Property instead of a Function/Sub

‘ 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

2 If we change the Array to a Collection, we need to End Function


change all code that reference the array directly.
‘ With this
To solve these problems we can create a function to return
the number of countries Property Get Count () As Long

‘ CLASS MODULE CODE - clsCountryList Count = UBound(arrCountries) + 1


‘ Array
End Function
Private arrCountries () As String In this scenario, there is not a lot of difference between
using the Property and using a function. However, there
Public Function Count () AsLong are differences. We normally create a Get and Let property
like this
Count = UBound(arrCountries) + 1
‘ CLASS MODULE CODE - clsAccount
End Function
Privated TotalCost As Double
We then use it like this
Property Get TotalCost () As Long
‘ MODULE CODE
Total Cost= dTotalCost
Dim oCountries As New clsCountries
End Property
Debug.Print “Number of countries is “ &oCountries.Count
Property Let Total Cost (dValue As Long)
This code solves the two problems we listed above. We
can change our Array to a Collection and the caller code
will still work e.g. dTotal Cost = dValue

‘ CLASS MODULE CODE End Property

‘ Collection Using Let allows us to treat the property like a variable.


So we can do this
Private collCountries() As Collection
oAccount.Total Cost = 6
Public FunctionCount() AsLong

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120 139

Copyright Free under CC BY Licence


The second difference is that using Let and Get allows Set coll2 = coll1
us to use the same name when referencing the Get or
Let property. So we can use the property like a variable. • Let is used to assign a value to a basic variable type.
This is the purpose of using Properties over a sub and
function. • Set is used to assign an object to an object variable.
In the following example, we use Get and Let properties
oAccount.TotalCost = 6
for a string variable
dValue = oAccount.TotalCost
‘ CLASS MODULE CODE
If we used a function and a sub then we cannot get the
‘ SET/LET PROPERTIES for a variable
behaviour of a variable. Instead we have to call two different
procedures e.g. Private m_sName As String
oAccount.SetTotalCost 6 ‘ Get/Let Properties
dValue = oAccount.GetTotalCost Property Get Name() As String
You can also see that when we used Let we can assigned Name = m_sName
the value like a variable. When we use Set Total Cost,
we had to pass it as a parameter.
End Property
The Property in a Nutshell
Property Let Name (sNameAs String)
1 The Property hides the details of the implementation
from the caller. m_sName = sName
2 The Property allows us to provide the same behaviour End Property
as a variable.
We can then use the Name properties like this
Types of VBA Property
Sub Test Let Set()
There are three types of Properties. We have seen Get
and Let already. The one we haven’t looked at is Set. Dim sName As String

Set is similar to Let but it is used for an object(see Dim coll As New Collection
Assigning VBA Objects for more detail about this).
Dim oCurrency As New clsCurrency
Originally in Visual Basic, the Let keyword was used to
assign a variable. In fact, we can still use it if we like. ‘ Let Property

‘ These line are equivalent


oCurrency.Name = “USD”
Let a = 7
‘ Get Property
a=7
sName = oCurrency.Name
So we use Let to assign a value to a variable and we use
Set to assign an object to an object variable End Sub

In the next example, we use Get and Set properties for an


‘ Using Let
object variable
Dim a As Long
‘ CLASS MODULE CODE
Let a = 7
Private m_collPrices As Collection
‘ Using Set
‘ Get/Set Properties
Dim coll1 As Collection, coll2 As Collection
Property Get Prices() As Collection
Set coll1 = New Collection
Set Prices = m_collPrices

140 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120

Copyright Free under CC BY Licence


End Property Msg Box “Class is being terminated”

Property Set Prices (collPricesAs Collection) End Sub

Public Sub Print Hello ()


Set m_collPrices = collPrices
Debug.Print “Hello”
End Property
End Sub
We can then use the properties like this
In the following example, we use Dim and New to create
Sub Test Let Set ()
the object.
Dim coll1 As New Collection
In this case, oSimple is not created until we reference it
for the first time e.g.
Dim oCurrency As New cls Currency
Sub Class Event sInit2 ()
‘ Set Property
Dim oSimple As New clsSimple
Set oCurrency.Prices = coll1
‘ Initialize occurs here
‘ Get Property
oSimple.PrintHello
Dim coll2 As Collection
EndSub
Set Coll2 = oCurrency.Prices
When we use Set and New together the behaviour is
EndSub different. In this case the object is created when Set is
used e.g.
We use the Get property to return the values for both items.
Sub Class Events Init()
Notice that even though we use the Get Property to return
the Collection, we still need to use the Set keyword to
Dim oSimple As clsSimple
assign it.
‘ Initialize occurs here
Class Module Events
Set oSimple = New clsSimple
A class module has two events
1 Initialize – occurs when a new object of the class is oSimple.PrintHello
created.
End Sub
2 Terminate – occurrs when the class object is deleted.
Note: For more information about the different
In Object Oriented languages like C++, these events are between using New with Dim and using New
referred to as the Constructor and the Destructor. In most with Set see Subtle Differences of Dim Versus
languages, you can pass parameters to a constructor but Set
in VBA you cannot. We can use a Class Factory to get
around this issue as we will see below. As said earlier, you cannot pass a parameter to Initialize.
If you need to do this you need a function to create the
Initialize object first

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”

End Sub PublicSubTest()

Private SubClass_Terminate() ‘ Use CreateSimpleObject function


IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120 141

Copyright Free under CC BY Licence


Dim oSimple As clsSimple Dim oSimple As clsSimple

Set oSimple = CreateSimpleObject(199.99) Set oSimple = NewclsSimple

End Sub ‘ Terminate occurs here

Public Function CreateSimpleObject(Price As Double) Set oSimple = Nothing


As clsSimple
End Sub
Dim oSimple As New clsSimple
If we don’t set the object to Nothing then VBA will
oSimple.Init Price automatically delete it when it goes out of scope.

Set CreateSimpleObject = oSimple What this means is that if we create an object in a


procedure, when that procedure ends VBA will delete any
End Function objects that were created.

We will expand on this CreateSimpleObject in Example Sub Class EventsTerm2()


2 to create a Class Factory.
Dim oSimple As New clsSimple
Terminate
‘ Initialize occurs here
The Terminate event occurs when the class is deleted.
This happens when we set it to Nothing oSimple.PrintHello

Sub Class EventsTerm () ‘ oSimple is deleted when we exit this Sub calling Terminate

EndSub

142 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.3.121
COPA - Using Accounting Software

Introduction to Tally, Features and Advantages


Objectives: At the end of this lesson you shall be able to
• explain about the tally software & history of Tally
• features of the tally software
• advantages of the tally software.

Introduction to Tally : Tally is an complete accounting mats in to the current data format. This is possible though
software. It is a versatile and massive software package, Import of Data Facility.
being used by various types of business Organisations.
Tally 6.3: Tally 6.3 is extended enterprise systems whereby
History of Tally it interacts with other system through ODBC (Open Data
Base Connectivity) you and e-mail upload your financial
Tally is a complete business solution for any kind of Busi- records form tally.
ness Enterprise. It is a full fledged accounting software.
Tally 7.2: This version is an integrated enterprise system
The Initial Release of Tally was Tally 4.5 version. This is provides different kind of taxes like VAT, TDS & TCS and
DOS (MS-DOS) based software released in the beginning Service Tax modules is introduced in this version.
of 1986's. It had Basic Financial Accounting / Book Keep-
ing Tools. Personal computers had gaining popularity in Tally 8.1: Tally 8.1 is multi language support software. It
India those days. supports 10 Languages includes is introduced in this ver-
sion.
Peutronics (The Company that develops Tally) used this
opportunity and put their Tally Version 4.5 on the market. Tally 9.0: This version is an improved model over the ver-
sion 8.1. it supports 13 Languages (Includes Foreign Lan-
Auditors and Accountants who used to maintain large vol- guages). Payroll, POS (Point of Sales) modules is intro-
umes of hard-bound notebooks were amazed at the abil- duced in this version.
ity of Tally to calculate Balance sheets and Profit Loss
accounts within seconds. All you need to do is just create Tally.ERP9: This is the latest version which provides dif-
Ledgers and enter vouchers. Tally will do the rest. It will ferent features like remote access,much powerful data
create all the statements, Trial Balance and Balance Sheet security, tally.net and many more.
For you.
Tally ERP9 is considered as the latest version.
The subsequent Tally releases are Tally 5.4, Tally 6.3,
Tally 7.2, Tally 8.1 and Tally 9.0, Tally ERP (Enterprise Features of Tally
Resources Planning). These release Include support for
Inventory used to stock maintenance of the company, 1 Accounting Features
Payroll which used to employee salary calculation and
wages payments and Multi Lingual support in Many In- i Handles different types of vouchers
dian languages Hindi, Tamil, Telugu, Kannada, Malayalam, - Payments Receipt
Gujarati, Marathi and more.
- Journals
Versions of Tally: - Debit Notes
Tally 4.0 & Tally 4.5: This version MS-DOS support finan- - Credit Notes
cial accounting system. It takes care of accounting activi- - Sales Notes
ties only such as Ledgers Classification Vouchers Entry.
It provides simple financial reports and bill wise analysis - Purchase Notes
of debtors and creditors in the business. - Receipt Notes

Tally 5.0: This version is an upgraded version to tally 4.5 - Delivery Notes etc.
and it works in windows operating system Inventory mod- ii Handles Primary Books of Accounts
ules is introduced in this version, which involves detailed
inventory, structure invoicing and integrating accounting - Cash Book
and Inventory records. - Bank Book

Tally 5.4: This version is an improved module over the ver- - Ledger
sion 5.0 where it is capable of converting earlier data for-

143

Copyright Free under CC BY Licence


- Purchase registers 5 Technological features
- Sales Registers etc.,
- Tally allows importing data from other software as
iii Used to prepare Statement of Accounts well as exporting data from tally.
- Trial Balance - ODBC connectivity is available in Tally. We can
connect applications like MS Word, MS Excel,
- Profit and loss Accounts
Oracle and can use data from tally directly.
- Trade Accounts
- While working with tally, we can e-mail, browse a
- Balance Sheet website. We can send a report on document directly
- Funds Flow from tally.

- Cash Flow - We can upload reports on the website directly from


tally.
2 Financial Management Features - Protocol support for HTTP, HTTPS, FTP, SMTP,
ODBC and RAW sockets with data interchange
- We can get closing stock value as entered in stock formats like XML, HTML, related formats.
ledgers by non-integrating Accounts and Inventory.
- Daily Balances and Transactions value can be got. Advantages of the Tally

- Funds flow and cash flow statements to track 1 Simple and Rapid Installation
movement of cash and funds in the company.
- Tally.ERP9's installation is a wizard driven, simple
- Tally computes interests as per book date. and speedy process involving minimal user-
- Tally provides Budgeting option. intervention. The software occupies tiny space and
can be installed on any drive. Tally.ERP9 supports
- Ratio Analysis provides important performance ratios installation on multiple systems connected to a
that give the pulse of the corporate health. network with different operating systems
(Windows98, NT, 2000, XP and Windows7)
3 Inventory Management Features
2 Auto Backup and Restore
- Flexible invoicing and billing terms.
- Flexible units of measure. - Tally.ERP9 provides automatic backup facility to
secure your company from any kind of data loss /
- Stock Transfer-Tally provides stock journal. corruption and helps in smooth functioning of your
- Stock query provides all relevant information for any business. Tally.ERP9 safeguards your data from any
stock item in a single screen. loss due to power failure or improper shutdown of
the system.
- Multiple stock valuation methods like FIFO, LIFO
and average methods are enhanced in Tally. 3 Tally Audit

4 Security Features - Tally.ERP9 audit feature allows you to verify, validate


and accept accounting information based on the
- The system administrator can define multiple levels masters, users and transactions (vouchers).
of security. Hence can credit, authorize-users,
assign passwords and assign specific task rights. 4 Split Company Data
- Tally offers data encryption (Tally vault) and follows
Data Encryption Standard (DES) Encryption - Tally.ERP9 allows splitting of company data into
methods. multiple companies for the required financial period.
Once the data is split, the closing balances of the
- Tally provides options for data backup in floppy/hard previous period are automatically carried forward as
disk and restoration of backup data. the opening balance for the subsequent period.
- Tally locker: It is a small portable hardware device
of a thumb size with storage capacity of 16MB. We 5 Import and Export of Data
can store data and work directly at tally locker. When
the task is over, we can simply keep it in our pocket. - Tally.ERP9 allows you to flexibly export and import
It is also used for backup. data in various formats such as MS EXCEL, JPEG,
PDF, XML, HTML or ASCII format.

144 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.121

Copyright Free under CC BY Licence


6 Graphical Analysis of Data Tax, TCS (Tax Collected all Source), TDS (Tax
Deducted at Source), FBT (Fringe Benefit Tax), GST
- Tally.ERP9 allows easy analysis of results / reports (Goods and Service Tax).
with graphical representation of values.
8 E-Mail Facility
7 Duties and Taxes
- Tally.ERP9 supports mailing of required information
- Tally.ERP9 allows Statutory Reporting for VAT to intended recipients and also mass mailing facility
(Value Added Tax), CST (Central Sales Tax), Service for certain reports like Payslip etc.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.121 145

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.3.122
COPA - Using Accounting Software

Implementing Accounts in Tally - Basics of Accounting, Golden Rules of


Accounting, Voucher Entry, Ledger Posting, Final Accounts Preparation
Objectives: At the end of this lesson you shall be able to
• explain the tally software screen
• understand accounting, its types, terms used
• understand golden rules of Accounting
• state about the journals, ledgers with entry posting methods
• prepare cash book, bank book etc.
• know shortcut keys.
Tally Software : In Gateway of Tally the following option is
display. (Fig 1)

Fig 1

Screen of the Tally 4 Single or Multiple User


5 System Day and Date
Tally Screen: Tally screen can be divided into following
four broad parts. 6 System Time

1 Product info Button Bar: Buttons appearing in the button bar (at right
of the screen) provide quick access to different options.
2 Button bar
Buttons on the button bar is context sensitive, different
3 Calculator buttons appear at different screens.
4 Work area
Calculator: By default the work area becomes active and
calculator remains inactive. Press Ctrl + N that would
Product info: Product info bar in Tally.ERP9 consisting
activate the calculator when calculator is active, we can
of the information about the product.
enter value and operators.
1 Developer company
The calculator follows BODMAS rule that indicates the
2 Software version and Release execution sequence: Bracket, Power, Division,
3 Software Serial Number Multiplication, Addition and Subtraction.

146

Copyright Free under CC BY Licence


Work area remain inactive and by default cursor would appear on
Create Company option.
The work at Gateway is broadly separated into two
sections. Buttons at gateway

1 The right hand side contains the popup menu, where Help (Hotkey: Alt+H): This button launches "Tally Reference
we would select instructions to Tally. Manual. This is a compiled HTML Help file. Normally on
clicking this button, the relevant content in respect of the
2 The left hand side displays list of selected companies.
screen would be displayed. If no context sensitive Help
On left part of the screen exists, contents would be displayed. We can select the
topic we wish to view.
Current Period
Web browser (Hot key: Alt+W)
Financial period with which we are working is displayed
for reference. To change the Financial period click This button launches the default installed web browser.
"F2:period" button in the button bar or press <Alt> + <F2>. For example, internet explorer is the default web browser,
on clicking the button IE will be loaded. The browser will
Current Date appear within the work area of the tally screen. All other
areas of Tally screen still remains in the screen.
It is not the calendar date but the date we worked last
during the current period. Vouchers will have the same F1- Select cmp (Hoy key: F1)
date as of current date. To change current date click
"F2:Date" button in the button bar or press F2. This button will display the list of companies. Move the
highlight bar and press <Enter> key to select a particular
List of selected companies company. Or simply press F1 key on the keyboard.

Name of all selected companies with last date voucher Introduction to Accounting
entry is displayed here. If we select more than one
company, the active company is shown at the top of list in It is the language of business through which normally a
bold face and others appear next in normal fonts. business house communicates with the outside world.

On right part of the screen Accounting may be defined as "the art of


recording, classifying summarising and
Gateway of Tally menu analysing transactions in the books of
accounts".
Primary choices of menu is displayed. The menu
operations are dependent on selection/activation of Accounting and accountancy are often synonymous terms.
operations. In some cases, we may find some operations
grayed indication that the option is not active. Accounting can be classified into two parts.

For example, upon selecting a company maintaining 1 Financial accounting


Accounts only, Inventory Info and stock summary options
2 Management Accounting
would be grayed.
Financial Accounting
Selections of menu
The accounting for revenues, expenses assets and liabilities
We can select a menu in either of the following mode: that is commonly carried on in the general offices of a
business is termed as Financial Accounting.
1 Press the highlighted character. For example, to select
create company, press 'C' the highlighted character. Its aim is to ascertain the profit or loss and to state the
financial position of the business as at a particular date.
2 Move highlight bar on the option with Up/Dn arrow key
and press<Enter>.
Scope of Financial Accounting
3 Using mouse double click the option. (We have to click
twice very fast). 1 Recording information in account books like journals,
cashbooks etc
Company Info Menu
2 Classifying the accounts using ledger.
On loading Tally, by default, Company Info menu appear
3 Summarising the information as statements like (1)
to select a company we wish to work with. If we are
Trial balance (2) Income statement and (3) Balance
installing Tally first time. select company option would
sheet

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 147

Copyright Free under CC BY Licence


Management Accounting Current Asset means the things and properties for resale
ie. The asset converts into cash. Eg. A cloth shop owner
The term management accounting refers to accounting for buys cloth for resale. Stock of cloth is current asset.
the management. The management accounting provides
information to the management so that planning, organis- Liabilities
ing directing and controlling of business operations can be
done in an orderly manner. All the amounts payable by a business concern to outsid-
ers are called liabilities.
Scope of Management Accounting
Capital
Following areas are identified within management ac-
counting Capital is the amount invested for starting a business by a
person.
1 Financial accounting
Debtor
2 Cost accounting
3 Revaluation accounting Debtor is the person who receives benefit without giving
money or moneys worth immediately, but liable to pay in
4 Budgetary control
future. i.e. the person owes amounts to the businessman.
5 Inventory control
Creditor
6 Statistical methods
7 Interim Reporting Creditor is the person who gives benefit without receiving
money or money's worth immediately but ot claim in fu-
8 Taxation
ture. i.e. the personto whom amounts are owed by the
9 Office services businessman.
10 Internal Audit
Debit: The receiving aspect of a transaction is called debit
or Dr.
Accounting terms
Credit: The giving aspect of a transaction is called credit
Business transaction
or Cr.
A business transaction is "The movement of money and
Drawings
money's worth form one person to another" or exchange
of values between two parties.
Drawings are the amounts withdrawn (taken back) by the
businessman from his business for his personal, private
Purchase means goods purchased by a businessman
and domestic purpose. Drawings may be made in the form
from suppliers.
cash, goods and assets of the business.
Sales is goods sold by a businessman to his customers.
Receipts
Purchase Return or Rejection in or Outward Invoice
It is a document issued by the receiver of cash to the giver
Purchase return means the return of the full or a part of of cash acknowledging the cash received voucher.
goods purchased by the businessman to his suppliers.
Account
Sales Return or Rejection out or Inward Invoice
Account is a summarized record of all the transactions
Sales return means the return of the full or a part of the relating to every person, everything or property and every
goods sold by the customer to the businessman. type of service.

Assets Ledger

Assets are the things and properties possessed by a busi- Ledger is the main book of account. It is the book of final
nessman in business. entry where accounts lie.

Two types of Assets Journal

Fixed Asset means the asset remain in business of Journal is a book of first entry. Transactions are entered in
use and not for resale. Eg. A shop owner purchase the journal before taken to the appropriate ledger accounts.
buildings, typewriter, showcases

148 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122

Copyright Free under CC BY Licence


Trial Balance Personal Accounts

It is a statement of all the ledger account balances pre- Impersonal Accounts


pared at the end of particular period to verify the accuracy
of the entries made in books of accounts. Impersonal Accounts can be further divided into two types.

Profit 1 Real Account


2 Nominal Account
Excess of credit side total amount over debit side total
amount.
Personal accounts are the accounts of persons, firms,
concerns and institutions which the businessmen deal.
Loss
Principles: Debit the receiver, Credit the giver
Excess of debit side total amount over credit side total
amount. Real Account: These are the accounts of things, materi-
als, assets & properties. It has physical existence which
Profit and loss account
can be seen & touch. Ex. Cash, Sale, Purchase, Furni-
ture, Investment etc.
It is prepared to ascertain actual profit or loss of the busi-
ness.
Principles: Debit what comes in, Credit what goes out
Balance Sheet
Nominal account: Nominal account is the account of
services received (expenses and Losses) and services
To ascertain the financial position of the business. It is a
given (income and gain) Ex. Salary, Rent, Wages, Statio-
statement of assets and liabilities.
nery etc.
Types of accounts
Principles: Debit all expense/losses, Credit all income/
gains
Accounts can be divided into two major types.
We can clearly understand the classification of accounts
in the following Figure 1.

Fig 1

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 149

Copyright Free under CC BY Licence


GOLDEN RULES OF ACCOUNTING

Account type Rules

Personal Accounts Debit the Receiver Credit the Giver


Real Accounts Debit what comes in Credit what goes out
Nominal Accounts Debit all expenses & losses Credit all incomes & gains

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

Date Particulars Amount Date Particulars Amount

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

DOUBLE ENTRY VS SINGLE ENTRY

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

2 Maintains a complete record of An incomplete record. Only personal accounts and


a Personal accounts cash accounts are maintained
b Real accounts and
c Nominal accounts

3 A balance sheet and profit and loss statement can A balance sheet and profit and loss statement cannot
be prepared conveniently, since the books of be conveniently prepared since the accounting
accounts present a complete picture records are incomplete

4 Double Entry is a complete, scientific system of Single Entry is not a system. It is incomplete
keeping books of accounts and unscientific

150 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122

Copyright Free under CC BY Licence


Personal Account - Examples: Cash goes out of the business and hence cash account
should be credited
1 Sold goods to Selvan on credit Rs.1,100/-
6 Paid rent Rs.250/-
Selvan account receives a benefit and hence should be
Cash goes out of the business and cash should be
debited
credited
2 Returned damaged goods to Sami.
In the above examples Sales Account Cash Accounts
Sami account receives a benefit and hence should be are real accounts. They are credited as per Rule.
debited
Nominal Accounts Examples:
3 Proprietor Thiru Anbu withdraws cash Rs.500 for house
hold expenses
1 Paid Rent Rs.250/-
Anbu - Drawing account receives a benefit and hence
Rent is an expense account. Hence rent account
should be debited
should be debited
In the above examples selvan a/c, Sami a/c, and Anbu
2 Paid salary Rs.1,200/-
- Drawings a/c are Personal accounts. They are
receivers of benefits and hence should be debited. Salary is an expense account. Hence salary account
should be debited
4 Anbu started business with cash Rs.50,000/-
3 Purchase of paper, pencils, ink, cover’s etc., for
Anbu - Capital a/c gives benefit in the form of cash to
Rs.250/-
business. Hence capital a/c should be credited
These are stationary items and expense items. Hence
5 Bought goods from Somu on credit for Rs.1,700/-
stationery account should be debited
Somu a/c gives a benefit and hence should be credited
In the above three examples Rent account, salary
6 Received five chairs from Godrej Co. at Rs.45 per chair account and stationery account all are nominal ac-
on credit basis counts. They are debited since they are expense items
Godrej Co a/c gives benefit in the form of 5 chairs. 4 Received commission Rs.500/-
Hence godrej co a/c should be credited.
Here commission is income to the business and hence
In the above examples capital a/c, Somu a/c and Godrej commission account should be credited.
a/c are personal accounts. They are giving benefits.
5 Received interest on loan given to B Rs.100/-
Hence their accounts should be credited.
Interest is income to the business. Hence interest
Real Account - Examples Account should be credited.

1 Bought five chairs [ furniture] from Godrej Co. at Rs.45 In the above two examples commission account and
per chair on credit basis. interest account are Nominal accounts. They have been
credited since they are incomes.
Furniture worth Rs.225 have come into the business as
per Rule, Debit what comes in. Since Furniture has
Books of Accounts
come in, Furniture Account should be debited.
2 Anbu started business with cash Rs.50,000/- Books of accounts can be generally classified into three
categories.
Cash of Rs.50,000 has come into the business and
hence cash account should be debited
1 Journal
3 Purchased goods from Somu on credit for Rs.1,700/-.
2 Ledger
Goods are bought in the aspect of purchases. Hence
3 Subsidiary Books
purchases account should be debited.
In the above examples, Furniture Account, cash ac- Journal : Journal is a book of prime entry. When a
count and purchases account are real accounts. Since transaction takes place, it is recorded in the Journal.
they have come into business, the accounts are deb- Layout of a Journal
ited.
4 Sale of goods to Selvan on credit Rs.1,100/- Date Particulars L.F. Dr. Cr.
(1) (2) (3) (4) (5)
Goods have gone out of the business hence sales
account is credited
5 Paid cash to Somu Rs.1,700/-

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 151

Copyright Free under CC BY Licence


L.F means Ledger Folio. The L.F column is meant for Example 2
recording the page number of the concerned account in the
Ledger. The transactions recorded in the journal will be July 7, 2003 : Bought goods for cash Rs.1543.
posted to the appropriate accounts in the Ledger.
1 Purchase Account and Cash Account are affected.
Journalising : Journalising is the process of analysing the
2 Purchase Account and cash accounts are Real ac-
business transaction under the heads of debit and credit
counts.
and recording them in the journal.
3 Purchase Account should be debited since goods have
When journalising a transaction the following steps to be come into business. Cash account should be credited
followed. since cash has gone out.

1 What are the accounts affected? name them.


2 What type of accounts are they? Identify them. e.g., Date Particulars L.F. Dr. Cr.
Personal, Real or Nominal Rs. P. Rs. P.

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)

Muthu account is a personal account Dr. Cr.


3 According to Rule No.2 Cash Account should be
debited because cash comes into the business. Debit Purchase of Asset Credit sale of asset

According to Rule No.1, Muthu Account should be


credited since Muthu has given benefit. Salary Account (Nominal Account)

Journal Dr. Cr.

Date Particulars L.F. Dr. Cr. Debit expenses in normal


Rs. P. Rs. P. account

2003 Cash Account Dr. 2 500 00


July 1st To Muthu Account 41 500 00
(Being cash
received from Muthu)

152 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122

Copyright Free under CC BY Licence


The account end with “Dr” is to be debited in the Ledger. The
Interest received account (Nominal a/c) account starts with “To” is to be credited in the Ledger. It
is customary to write “To” on the debit side and “By” on the
Dr. Cr. credit side.

Credit gains in Nominal Example:


accounts
Given the journal Entry

Posting in the Ledger : The technique of recording the


journal entries into the ledger is known as posting.

Date Particulars L.F. Dr. Cr.


Rs. p. Rs. p.

2003 Cash Account Dr. 75,000 00


July 1st To Capital Account 75,000 00
(Being the amount invested in business)

Capital account starts with “To”. So the capital account is


credited with the entry in the credit side as “By cash”.

CAPITAL ACCOUNT
Dr. Cr.

Date Particulars Amount Date Particulars Amount


Rs. P. Rs. P.

2003
July 1 By cash 75,000 00

JOURNAL VS LEDGER

S.No. Journal Ledger


1 The journal is a subsidiary book The ledger is the main book of accounts
2 Transactions are first entered in Journal Entries in the journal are posted in the Ledger.
3 Journal is a daily record. Business transactions are Posting from journal to Ledger is done periodically,
entered in this book in the order of dates may be weekly or fortnightly.
4 Entering the transaction in the journal is called The act of recording journal entries into ledger
journalising is called “Posting”.

Subsidiary Books : Journal is sub-divided into smaller 4 Sales Returns Books


journals called subsidiary-journals. We can synonymously
5 Cash book
call subsidiary - journals as subsidiary books.
1 Purchase Book
Categories of subsidiary book includes the following.
– This book is also called as “Purchase Day book”,
1 Purchase Book.
“Invoice Book”, “Bought Book”, “Purchases Journal”.
2 Sales Book.
– It is used for recording credit purchases of goods.
3 Purchase Returns Books
– Cash purchases are not recorded in this book.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 153

Copyright Free under CC BY Licence


Layout of purchase book

Date Name of the Supplier L.F. Invoice No. Amount

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”

– It is used to record credit sales of goods.

Layout of the Sales Book

Date Name of the Customer L.F. Outward Invoice No. Amount

3 Purchase Returns Book – It is used to record transactions relating to return of


goods to suppliers.
– This book is also called as “Purchases Returns
Journal”, “Returns Outwards Book”.

Layout of Purchase Returns Book

Date Name of Supplier L.F. Debit Notes Nos. Amount

4 Sales Returns Book – It is used to record particulars of goods returned by


customers.
– This book is also called as “Returns Inwards Book”,
“Sales Returns Journal”.
Layout of Sales Returns Book

Date Name of Customer L.F Credit Note No. Amount

5 Cash Book – Cash book looks just like a ledger.

– The purpose of the cash book is to record all cash


receipts and payments and the sums deposited into
and with drawn from the bank.

154 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122

Copyright Free under CC BY Licence


Layout of Cash Book
Dr Cr

Date Particulars L.F. Amount Date Particulars L.F Amount

Accounts Information - Grouping Expenditure incurred during current year but the amount
on which is not yet paid. (Added to the expenditure on the
Current Asset: It is converted into cash with in a year. debit side and entered on the liability side.)
Ex. Bills receivable.
Income received in advance or Income received but
Direct Expenses: These are the expenses which are di- not earned.
rectly related to manufacturing of goods. Ex. Wages, fac-
tory rent, heating, lighting etc., Income received during the currentyear but not earned or
a part of which relates to the next year. (Deducted from
Indirect Expenses: These are the expenses which are the concerned income on the credit side and entered on
indirectly related to manufacturing of goods. Ex. Salary, the liability side)
rent, stationery, advertisement, printing.
Prepaid advance or Expenses
Depreciation: Decrease the value of the asset.
Expenditure paid during current year but not incurred or a
Sundry debtors: The person who is the receiver or cus- part of which related to the next year is called expenditure
tomer. prepaid.

Sundry creditors: The person who gives or supplier. Income outstanding means income earned during the cur-
rent year but the amount on which is not yet received.
Expenses Outstanding or Unpaid expenses or Expenses
due:

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 155

Copyright Free under CC BY Licence


Accounts information - Ledger - Grouping

Ledger Group

Cash at bank Bank Account

Bank overdraft Bank OD

Capital Capital Account

Cash in hand Cash in hand

Other Liabilities Current Liabilities

Bills receivable Current Asset

Stock of stationery Current Asset

Prepaid expenses Current Asset

Income outstanding Current Asset

Bills payable Current Liabilities

Expense outstanding Current Liabilities

Income received in advance Current Liabilities


Fixed deposit at bank Deposit

Fright charges Direct Expenses

Carriage inwards or Purchases Direct Expenses

Cartage and coolie Direct Expenses

Octroi Direct Expenses

Manufacturing wages Direct Expenses

Coal, gas, water Direct Expenses

Factory rent, insurance, electricity, lighting Direct Expenses


and heating

Loose tools Fixed Asset

Fixtures and fittings Fixed Asset

Furniture Fixed Asset

Motor Vehicles Fixed Asset

Plant and machinery Fixed Asset

Land and building Fixed Asset

Leasehold property Fixed Asset

Patents Fixed Asset

Goodwill Fixed Asset

Salary Indirect Expenses

Postage and Telegrams Indirect Expenses

Telephone charges Indirect Expenses

Rend paid Indirect Expenses

156 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122

Copyright Free under CC BY Licence


Rates and taxes Indirect Expenses

Insurance Indirect Expenses

Audit fees Indirect Expenses

Interest on bank loan Indirect Expenses

Interest on loans paid Indirect Expenses

Bank charges Indirect Expenses

Legal charges Indirect Expenses

Printing and stationery Indirect Expenses

General expenses Indirect Expenses

Sundry expenses Indirect Expenses

Discount allowed Indirect Expenses

Carriage outwards or sales Indirect Expenses

Travelling Expenses Indirect Expenses

Advertisement Indirect Expenses

Shortcut Keys

F1 Select Company F6 Receipt Records all receipts into bank or cash ac


counts.
Alt+F1 Shut Company

Alt+F3 Company information menu F7 Journal Records adjustments between ledger ac


counts
Ctrl+A To accept a form wherever you use the key
combination the screen or report will be ac F8 Sales Records all sales.
cepted as it is on this screen.
Ctrl+F8 Credit note voucher
Alt+C To create a master at a voucher screen.
F9 Purchase Records all purchase.
Alt+D To delete a voucher/To delete a master.
Ctrl+F9 Debit note voucher
Ctrl+Enter To alter a master while making an entry or
viewing report. F10 Reversing Journal voucher

F2 Date Alt+2 To duplicate a voucher

Alt+F2 Change period Alt+C To create a Master at a voucher screen

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

Ctrl+N Calculator screen. Alt+R To remove a line in a report in reports


screen
Ctrl+V Voucher mode (Cr. Dr)/Invoice mode (name
of item, rate, quantity, and amount) Alt+S To bring back a line, you removed using
Alt+R in reports screen
F4 Contra Records funds transfer between cash and
bank accounts Alt+X To cancel a voucher in Daybook/List of
vouchers
F5 Payment Record all bank and cash payments

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 157

Copyright Free under CC BY Licence


Journalize the following transactions 8 Paid cash to Mr. X Rs.1,000/-

1 Commenced business with cash Rs.50,000/- 9 Received commission Rs.50/-

2 Deposit into bank Rs.15,000/- 10 Received interest on bank deposit Rs.100/-

3 Bought office furniture Rs.3,000/- 11 Paid into bank Rs.1,000/-

4 Sold goods for cash Rs.2,500/- 12 Paid for advertisement Rs.500/-

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/-

7 Received cash form Mr. Y on account Rs.2,000/- 15 Paid salary Rs.5,000/-

158 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122

Copyright Free under CC BY Licence


Gateway of Tally - Account info - Ledger - Create
Gateway of Tally - Account voucher

Sl.No. Key Voucher Ledger Group Types of Principles Amount


account
Cr. Capital Capital Personal Giver 50,000
account
1 F6 Receipt
Dr. Cash Cash in hand Real Comes in 50,000
Cr. Cash Cash in hand Real Goes out 15,000
2 F4 Contra
Dr. Bank Bank account Real Comes in 15,000
Dr. Furniture Fixed asset Real Comes in 3,000
3 F5 Payment
Cr. Cash Cash in hand Real Goes out 3,000
Dr. Cash Cash in hand Real Comes in 2,500
4 F8 Sales
Cr. Sales Sales account Real Goes out 2,500
Cr. X Sundry Personal Giver 2,000
creditor
5 F9 Purchase
Dr. Purchase Purchase Real Comes in 2,000
account
Dr. Y Sundry debtors Personal Receiver 3,000
6 F8 Sales
Cr. Sales Sales account Real Goes out 3,000
Cr. Y Giver 2,000
7 F6 Receipt
Dr. Cash Cash in hand Real Comes in 2,000
Dr. X Reciever 1,000
8 F5 Payment
Cr. Cash Cash in hand Real Goes out 1,000
Cr. Commission Indirect Nominal Credit all 50
income income
9 F6 Receipt
Dr. Cash Cash in hand Real Comes in 50
Cr. Interest on Indirect Nominal Credit all 100
bank deposit income income
10 F6 Receipt
Dr. Bank Bank account Real Comes in 100
Cr. Cash Cash in hand Real Goes out 1,000
11 F4 Contra
Dr. Bank Bank account Real Comes in 1,000
Dr. Advertisement Indirect Nominal Debit all 500
expenses expenses
12 F5 Payment
Cr. Cash Cash in hand Real Goes out 500
Cr. Cash Cash in hand Real Goes out 800
13 F9 Purchase
Dr. Purchase Purchase Real Comes in 800
Cr. Cash account
Dr. Cash Cash in hand Real Comes in 1,500
14 F8 Sales
Cr. Sales Sales account Real Goes out 1,500
Dr. Salary Indirect Nominal Debit all 5,000
expense expenses
15 F5 Payment
Cr. Cash Cash in hand Real Goes out 5,000

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 159

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.3.123
COPA - Using Accounting Software

Financial Accounting Reports


Objectives: At the end of this lesson you shall be able to
• understand financial accounting
• understand book-keeping
• prepare trading account, profit and loss account & balance sheet.

Introduction: The accounting for revenues, expenses, Trading Account : Trading refers to buying and selling of
assets and liabilities that is commonly carried on in the goods. Trading account shows the result of buying and
general offices of a business is termed as Financial selling of goods. This account is prepared to find out the
Accounting. difference between the selling price and cost price.

Its aim is to ascertain the profit or loss of the business and – If the selling price exceeds the cost price, it will bring
states the financial position of the business as at a Gross Profit. For example, If the goods of cost price
particular date. Rs.50,000 are sold for Rs.60,000 that will bring in Gross
Profit of Rs.10,000.
Financial accounting includes the following activities. – If the cost price exceeds the selling price, it will bring
Gross loss. For example, if the goods of cost price
i Book keeping Rs.60,000 are sold for Rs.50,000, that will result in
ii Preparation of Trading Account Gross Loss of Rs.10,000
iii Preparation of profit and loss account Thus Gross Profit or Gross Loss is indicated in Trading
Account.
iv Preparation of Balance Sheet
Items appearing in the Debit side of Trading account
Book-keeping : Book-keeping is the art of recording 1 Opening Stock : Stock on hand at the commence-
business transactions in a systematic manner. Main ment of the year or period is termed as the opening
objective of book-keeping is to calculate the profit or loss stock
of a business accurately.
2 Purchases : It indicates total purchases both cash and
We have discussed various types of Books of accounts in credit made during the year
the previous chapter. 3 Purchases returns or Returns outwords : Purchases
Advantages of Book-Keeping Returns must be subtracted from the total purchases to
get the net purchases. Net purchases will be shown in
1 Book-keeping provides reliable record of transactions
the trading account.
essential for ready reference.
4 Direct Expenses on Purchases : Some of the Direct
2 Profit or loss is ascertained using Books of accounts
Expenses are
3 Calculation of due amount the businessman has to pay
a Wages: It is also known as productive
others is done using Books of accounts
wages or Manufacturing wages
4 Borrowings and Assets are controlled.
b Carriage or carriage Inwards:
5 Financial position and growth of business is ascer-
c Octroi Duty : Duty paid on goods for
tained
bringing them within municipal limits
6 Do’s and Don’ts are identified
d Customs duty, Dock duty, clearing
7 Book-keeping is used for taxation and fixing selling charges, Import duty etc.,
price.
e Fuel, Power, Lighting charges related to
Final Account : Trading, Profit and Loss account, Balance production
sheet are prepared at the end of the year or at the end of
f Oil, Grease and Waste
the part. So it is called Final Account.
g Packing charges: Such expenses are
– Trading, Profit & loss account is prepared to find out
incurred with a view to put the goods in a
profit or loss of the organisation
saleable condition.
– Balance sheet is prepared to find out the financial
Items appearing on the credit side of trading account
position of the organisation
1 Sales: Total sales (Including both - cash and credit)
made during the year or period

160

Copyright Free under CC BY Licence


2 Sales Returns or Return Inwards: Sales returns 3 Closing stock: Generally, closing stock does not
must be subtracted from the Total sales to get Net appear in the Trial Balance. It appears outside the Trial
sales. Net sales will be shown Balance. It represents the value of goods at the end of
the trading period.

Specimen form of a trading a/c


Dr. Trading Account for the year ending Cr.

Particulars Amount Amount Particulars Amount Amount


Rs. P. Rs. P. Rs. P. Rs. P.

To Opening stock xxxx By sales xxxx


To Puchase xxxx Less: Returns
Less : Returns-outwards xxxx Inwards xxxx xxxx
To wages xxxx By closing stock xxxx
To Freight xxxx By Gross loss xxxx
To Carriage Inwards xxxx (to be transferred to P&L A/c)
To Clearing charges xxxx
To Packing charges xxxx
To Dock dues xxxx
To Power xxxx
To Gross Profit xxxx
(to be transferred to P&L A/c)

xxxx xxxx

Balancing of Trading Account : The difference between Advantages of Trading Account


the two sides of the Trading account, indicates either
Gross Profit or Gross loss. If the total on the Credit side is 1 The results of purchases and sales can be clearly
more, the difference represents Gross Profit. On the other assertained.
hand, if the total of the debit side is high, the difference 2 Gross profit ratio to sales could also be easily ascer-
represents Gross loss. The Gross Profit or Gross Loss is tained. It helps to determine price
transferred to Profit & Loss A/c.
3 Gross profit ratio to direct expenses could also be
Closing Entries of Trading A/c : Trading account is a easily ascertained. And so, unnecessary expenses
ledger account. Hence no direct entries should be made in could be eliminated
the trading account. Several items such as purchases, 4 Comparison of trading account details with previous
sales are first recorded in the journal and then posted to year details help to draw better administrative policies.
the ledger. The same accounts are closed by transferring
them to trading account. Hence it is called as closing Example 1
entries. Prepare a trading account from the following informations
of a trader
i Total purchases made during the year 2002 Rs.20,000
ii Total sales made during the year 2002 Rs.25,000

Trading account for the year ending 31st December 2002


Dr Cr.
Particulars Amount Particulars Amount
Rs. P. Rs. P.

To purchases 20,000 By sales 25,000


To Gross profit c/d 5,000

25,000 25,000
Example 2
ii Purchases Rs.16,100
Prepare a Trading Account from the following informations
iii Sales Rs.30,600
of a trader.
iv 2002 Dec 31 Closing Stock Rs.3,500
i 2002 Jan 1 Opening stock Rs.5,000
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123 161

Copyright Free under CC BY Licence


Trading Account for the year ending 31-12-2002
Dr Cr.

Particulars Amount Particulars Amount


Rs. P. Rs. P.

To opening stock 5,000 By sales 30,600


To purchases 16,100 By Closing stock 3,500
To Gross profit c/d 13,000
(Transferred to P&L a/c)
34,100 34,100

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.

To Trading a/c xxxx By Trading a/c xxxx


(Gross loss) (Gross profit)
To Salaries xxxx By Commission earned xxxx
To Rent & Taxes xxxx By Rent received xxxx
To Stationaries xxxx By Interest received xxxx
To Postage expenses xxxx By Discounts received xxxx
To Insurance xxxx By Net loss xxxx
To Repairs xxxx (Capital account)
To Trading expenses xxxx
To Office expenses xxxx
To Interest xxxx
To Bank charges xxxx
To Establishment expenses xxxx
To Sundry expenses xxxx
To Commission xxxx
To Discount xxxx
To Advertisement xxxx
To Carriage Outwards xxxx
To Travelling expenses xxxx
To Distribution expenses xxxx
To Bad debts xxxx
To Depreciation xxxx
To Net profit xxxx
(transferred to Capital a/c)
xxxx xxxx

162 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123

Copyright Free under CC BY Licence


Example 3 iii Tax, Insurance Rs.1,400 Discount allowed Rs.600
iv Discount received Rs.400
Prepare profit and loss account from the following balances
of Dharani Enterprises for the year ending 31.12.2012 v Travelling expenses Rs.2,600
vi Advertisement Rs.3,600
i Office rent Rs.3,000 Salaries Rs.8,000
vii Gross profit transferred from the trading account
ii Printing expenses Rs.2,200 Sationeries Rs.2,400
Rs.25,000
Profit and Loss Account of Dharani Enterprises for the year ending 31st Dec 2012
Dr Cr.
Particulars Amount Particulars Amount
Rs. P. Rs. P.

To Salaries 8,000 By Gross profit 25,000


To Office rent 3,000 (transferred from Trading a/c)
To Stationaries 2,400 By Discount received 400
To Printing expenses 2,200
To Tax, insurance 1,400
To Discount allowed 600
To Travelling expenses 2,600
To Advertisement 3,600
To Net profit 1,600
(Capital account)
25,400 25,400
Example 4 Sales Returns 5,000

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.

Particulars Amount Particulars Amount


Rs. P. Rs. P.

To Stock (15.01.1994) 15,000 By sales 3,00,000


To Purchases 1,65,000 Less returns 5,000 2,95,000
Less Returns 10,000 1,55,000 By closing stock 80,000
To Wages 10,000
To Gross Profit 1,95,000
3,75,000 3,75,000
To Salaries 5,000 By Gross profit 1,95,000
To Postage 300 (transferred from trading a/c)
To Bad depts 100 By discount received 500
To Carriage outwards 4,000
To Stationaries 1,000
To Interest 800
To Insurance 400
To Net profit 1,83,900
(Capital a/c) 1,95,500 1,95,500

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123 163

Copyright Free under CC BY Licence


If trial balance shows trading expenses as well Definition : The word “Balance Sheet’ is defined
as office expenses, the Trading expenses should as “ a statement which sets out the assets and
be shown in the trading account and office liabilities of a business firm and which serves to
expenses should be shown in profit and loss ascertain the financial position of the same on
account. On the otherhand if the trial balance any particular date”.
shown only a trading expenses, it should be
shown in the profit and loss account – On the left hand side of this statement, the liabilities and
capital are shown
In the trial balance, wages are clubbed with
salaries as ‘wages and salaries’. This item is – On the right hand side of this statement, all the assets
shown in Trading account. On the other hand, are shown
it appears as salaries and wages and this item – Hence both the sides of the balance sheet must be
is shown in the profit & Loss account. equal
Income tax : Income tax paid by a proprietor – Capital arrives assets exceeds the liabilities
is considered as personal expenses. So instead
of debited to Profit and Loss account, it should Objectives of Balance sheet
be debited to the capital account.
1 It shows accurate financial position of a firm
Balance sheet
2 It shows various transactions took place at a given
– Trading account provides the details of Gross Profit or period
Gross Loss 3 It indicates that, whether the firm has sufficient assets
– Profit and Loss account provides the details of the Net to repay in liabilities
Profit or Net Loss 4 The accuracy of final accounts is verified by this
– Besides the above, the proprietor wants statement
i to know the total assets invested in business 5 It shows the profit and loss arrived, through profit & Loss
account
ii To know the position of owner’s equity
iii To know the liabilities of business
SPECIMEN FORM OF A BALANCE SHEET:
BALANCE SHEET OF SUNIL ENTERPRISES AS AT 31.12.2012
Dr Cr.
Liabilities Amount Amount Assets Amount Amount
Rs. p. Rs. P. Rs. P. Rs. P

Sundry creditors xxxx Cash in hand xxxx


Bills payable xxxx Cash at Bank xxxx
Bank overdraft xxxx Bills receivable xxxx
Loans xxxx Sundry Debtors xxxx
Mortgage xxxx Closing stock xxxx
Reserve Fund xxxx Furniture & Fittings xxxx
Outstanding exp. xxxx Investments xxxx
Capital xxxx Plant & Machinery xxxx
Add: Net profit (or) Loose tools xxxx
Less: Net loss xxxx Land and Buildings xxxx
xxxx Business premises xxxx
Less: Drawings xxxx Horses & carts xxxx
xxxx Prepaid exp.
Less : Income tax xxxx xxxx Patents & Trade marks xxxx
Good will xxxx

xxxx xxxx

The Balance sheet contains two parts. Assets : Assets represent everything which a business
owns and has money value. Assets are always shown as
1 Left hand side the liabilities debit balance in the ledger. Assets are classified as
2 Right hand side the assets follows:

164 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123

Copyright Free under CC BY Licence


1 Tangible Assets : Assets which can be seen and felt Equation of Balance sheet
by touching are called Tangible assets. Tangible as-
sets are classified into two: Capital = Assets - Liabilities

a Fixed Assets : Assets which are durable in nature Liabilities = Assets - Capital
and used in business over and again are known as Assets = Liabilities + Capital
Fixed assets. E.g., Land and building, machinery,
trucks, etc., Trial Balance : When the transactions are recorded under
b Floating Assets or Current Assets : Current Assets double entry system, there is a credit for every debit. When
are one account is debited, another account is credited with
equal amount.
i Meant to be converted into cash
ii Meant for resale If a statement is prepared with debit balances on one side
and credit balances on the other side, the totals of the two
iii Likely to undergo change sides will be equal such a statement is called Trial
E.g: Cash, Bank Balance, stock, sundry debtor Balance.

2 Intangible Assets : Assets which cannot be seen and Advantages:


has no fixed shape. E.g., Good will, Patent
1 It is the shortest method of verifying the arithmetical
3 Fictitious Assets : Assets which have no real value and accuracy of entries made in the ledger. If the Trial
will appear on the assets side of balance sheet are balance agrees, it is an indication that the accounts are
known as fictitious assets. correctly written up. But it is not a conclusive proof.
Ex: Preliminary expenses, Discount on creditors 2 It helps to prepare the trading account, Profit and loss
account and balance sheet
Liabilities : All that the business owes to others are called
liabilities. It means that any amount which a business 3 It presents to the business man a consolidated list of all
concern has to pay legally. It also includes proprietor’s Ledger Balances.
capital. They are known as credit balances in ledger.
Sundry Debtors : There may be large number of deptors
Liabilities are classified as follows. to a trader. All the deptor’s names are not written in the trial
balance. A list of debtors with their individual debit bal-
1 Long term liabilities : Liabilities which will be re- ances are prepared and totalled. The total is written under
deemed after a long period of time say 10 to 15 years. the heading “Sundry Debtors” which appears in the Trial
e.g., capital, Long-term Loans 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

Trial Balance Balance Sheet

1 It shows the balances of all ledger accounts It shows the balances of personal and real accounts only
2 It is prepared after the completion of the ledger It is prepared after the completion of trading and
accounts or arrival of the balances profit and loss account
3 Its object is to check the arithmetical accuracy Its object is to reveal the financial position of the business
4 Items shown in the trial balance are not in order Items shown in Balance sheet must be in order
5 It shows Opening Stock It shows Closing Stock
6 It has the headings, debit and credit. It has the headings of Assets and Liabilities

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123 165

Copyright Free under CC BY Licence


Example 5

From the follwing trial balance extracted from the books of


Sundar & Sons as on 31.12.2012. Prepare i. Trading and
Profit and Loss account and ii. Balance sheet.

Trial Balance as on 31-12-2012


Dr. Cr.
Debit balances Amount Credit Balances Amount
Rs. P. Rs. P.

Cash in hand 2,000 Capital 2,00,000


Machinery 60,000 Sales 2,54,800
Stock 50,000 Sundry Creditors 40,000
Bills receivable 1,600 Bank overdraft 22,000
Sundry Debtors 50,000 Return outwards 3,000
Wages 70,000 Discounts received 1,800
Land 40,000 Bills payable 1,800
Carriage inwards 2,400
Purchases 1,80,000
Salaries 24,000
Rent 4,000
Postage 1,000
Return inwards 3,200
Drawings 10,000
Furniture 18,000
Interest 600
Cash at Bank 6,600

5,23,400 5,23,400

Stock as on 31-12-2012 is Rs.1,00,000

Trading, Profit & Loss account of Sundar & Sons for the year ending 31-12-2012
Dr Cr.
Particulars Amount Particulars Amount
Rs. P. Rs. P.

To stock (1-1-2012) 50,000 By sales 2,54,800


To purchases 1,80,000 Less Returns 3,200 2,51,600
Less returns 3,000 1,77,000 By closing stock 1,00,000
To wages 70,000
To carriage inwards 2,400
To Gross Profit c/d 52,200
(Transferred to P&L a/c) 3,51,600 3,51,600

To salaries 24,000 By Gross Profit b/d 52,200


To Rent 4,000 (Transferred from Trading a/c)
To postage 1,000 By discount received 1,800
To interest 600
To Net Profit 24,400
(capital a/c)
54,000 54,000

166 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123

Copyright Free under CC BY Licence


Balance sheet of Sundar & Sons as at 31.12.2012
Dr Cr.

Liabilities Amount Assets Amount


Rs. P. Rs. P.

Sundry creditors 40,000 Cash in hand 2,000


Bank overdraft 22,000 Cash at bank 6,600
Bills payable 1,800 Machinery 60,000
Capital 2,00,000 Bills receivable 1,600
Add: Net profit 24,400 Sundry debtors 50,000
Less: Drawings 2,24,400 2,14,400 Furniture 18,000
Land 40,000
Closing stock 1,00,000

2,78,200 2,78,200

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123 167

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.3.124
COPA - Using Accounting Software

Costing Systems
Objectives: At the end of this lesson you shall be able to
• understand costing, its types and cost classification
• differentiate budgeting and standard costing
• cost centre, cost category, cost centre reports
• inventory accounting with tally
• inventory report, inventory books, statement of inventory.

Introduction : Costing refers to fixing the costs of a Cost classification : Cost classification is the process of
product. The factors which determines the cost of a product grouping costs according to their common characteristics.
are known as elements of cost.
Costs may be classified according to their nature and
number of characteristics such as function, variability,
Elements of cost : There are three cost elements exist
controllability and normality.
in costing. They are
1 Nature : Costs are classified according to their nature
1 Material cost
as
2 Labour cost
a Materials cost
3 Expenses
b Labour cost
– Material cost refers to the cost of raw materials used
c Expenses
for production of a product.
– Labour cost refers to the wages paid to the workers 2 Function : According to the divisions of activity, costs
in the manufacturing department. can be classified as
– Expenses refers to the expenditure by the way of
a Production cost
rent depreciation and power cut.
b Admistrative cost
Concept of Direct and Indirect costs : The total expendi-
c Selling cost
ture may be classified as Direct cost and Indirect cost.
d Distribution cost
Direct cost : The expenditure which can be conveniently
allocated to a particular job or product or unit of service is 3 Variability : According to their behaviour in relation to
known as direct cost. changes in the volume of production cost can be
classified as
Direct expenditure is made up of
a Fixed cost
1 Direct materials
b Semi fixed cost
2 Direct labour
c Variable cost
3 Direct expenses
4 Controllability : Costs are classified according to their
Indirect cost : The expenditure which cannot be conven- influences by the action of a given member of an
iently allocated to a particular job or product or unit of undertaking as
service is known as indirect cost.
a Controllable cost
In a firm producting a larger variety of articles most of the
b Uncontrollable cost
expenditure apart from materials and labour will be indirect.
5 Normality : Costs are classified according to the costs
Indirect expenditure is made up of
which are normally incurred at a given level of output as
1 Works of factory expenses
a Normal cost
2 Office and administrative expenses
b Abnormal Cost
3 Selling and distributive expenses
Presentation of total cost : The presentation of total cost
according to their nature is shown here.

168

Copyright Free under CC BY Licence


Statement of total cost Add: Variable expenses ......................
“B” Marginal cost ......................
Rs.
Add: Fixed overhead ......................
Direct material cost ------------------
“C” Total cost ......................
Direct wage ------------------
Fixed and variable costs : Fixed costs are those costs
Direct expenses ------------------
which remain constant at all levels of production within a
“A” Prime cost ------------------ given period of time. In other words, a cost that does not
change in total but become, progressively smaller per unit
Add : Works on cost or when the volume of production increases is known as Fixed
Factory expenses ------------------ Cost. It is also called “Period Costs”.

“B” works cost ------------------ E.g., Rent, salary, Insurance charges, etc.,

Add: Office and administrative Variables costs are those costs which vary in accordance
Expenses ------------------ with the volume of output.

“C” cost of production ------------------ Absorption costing and Marginal Costing : Absorption
Add: Selling and Distribution costing is also termed as Traditional or Full Cost method.
In this method, the cost of a product is determined after
expenses ------------------ considering both fixed and variable costs. In absorption
“D” Cost of sale ------------------ costing all costs are identified with the manufactured
products.
Add: Profit or Less: loss ------------------
Marginal costing is a technique where only the variable
__________ costs are considered while computing the cost of a
“E” Selling price ------------------ product. The marginal cost of a product is in variable cost.
In this method only variable costs are changed to the cost
__________ units. Fixed cost is written against contribution for that
period.
The presentation of total cost according to their variability
is shown under. Hence we can derive a formula for contribution as under:
Statement of total costs Contribution = sale price - marginal cost
Rs. Standard costing : Standard costing is a specialised
technique of costing. In this costing standard costs are pre-
Direct Material cost ...................... determined. Actual costs are compared with pre-deter-
Direct wages ...................... mined costs. The variations between the two are noted and
analysed. Measures are taken to control the factors
Direct Expenses ...................... leading to unfavourable variations. Standard costing serves
“A” prime cost ...................... as an effective tool in the hands of the management for
planning, coordinating and controlling of various activities
of the business.
Budgeting Vs Standard costing

Budgeting 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.

3 It does not involve with standardisation of products. It requires standardisation of products.

4 Budgeting can be operated in part also. It is not possible to operate this system in parts.

5 Budget can be operated without any standards. Standard costing cannot exist without budget.

6 Budgets are maximum target of expenses above Standards are minimum targets which are to be attained
which actual expenses should not rise. by actual performance at specific efficiency level.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.124 169

Copyright Free under CC BY Licence


Cost Centres : Cost Centre is a location, person or item For example, a company has three departments such as
of equipment, in relation to which costs may be ascertained Marketing, Finance and Production. Each department has
and used for the purposes of cost control. been identified as a cost centre. The wages paid to the
respective workers of the department concerned is the
Any raw material, labour or other input used by an direct cost of that particular cost centre(department).
organisation for the manufacturing process is cost which However, if the rent of the building in which the production
is allocatable as direct or indirect costs to cost centres. departments are located is apportioned to the departments
on a scientific basis, then it is termed as an indirect cost
1 Direct Cost : A cost which is allocated to a cost centre of the cost centre.
is a direct cost of that particular cost centre.
This is the example of use of Cost Categories. The
2 Indirect Cost : A cost which is apportioned to different
Salesmen A, B and C can be Cost Centres under a
cost centres on a suitable basis is an indirect cost of
Category Executive. Similarly, you can create a new Cost
that particular cost centre.
Category projects under which Cost Centres such as
Cost Category: Cost Categories are useful for Airport construction, Road construction and Buildings may
organisations that require allocation of Revenue and Non- be created. So that the classification appears as following
Revenue Items to parallel sets of Cost Centres. The
examples of Cost Categories can be Region-wise, Grade-
wise, Department-wise and so on.

Cost Categories Departments Executives Projects

Marketing Salesman A Airport Construction

Cost Centres Manufacturing Salesman B Road Construction

Finance Salesman C Buildings

Analysis using Cost Centres : Cost centre performance Ledger Break-up: This report displays the summary
can be measured using volume or relative percentage. For information of all Cost Centers for the selected Ledger.
example. Direct variable cost can be monitored as a
percentage of sales or even as a percentage of cost of Group Break-up: This report displays the summary
production if there are effective process controls. Indirect information of all Cost Centers for the selected Group.
expenses can be monitored by creating a reasonable limit
on the amount to be spent. Inventory Accounting With Tally : Inventory accounting
includes recording stock details, the purchase of stock,
The following elements have to be kept in mind while the sale of stock, stock movement between storage
measuring cost performance. Location or Godowns, and providing information on stock
availability. With Tally it is possible to integrate the inventory
1 Overall objective of the business. and accounting systems so that financial statements
reflect the closing stock value from the inventory system.
2 Changes in the business environment.
3 Ground realities. The inventory system operates in much the same way as
the accounting system.
Cost Centres in Tally : In Tally's cost centre allow for
multi dimensional analysis of financial information. The • First you set up the inventory details, which is a similar
cost centre feature in Tally allows you to allocate a operation to creating the chart of accounts although,
transaction to a particular cost entre, gives the cost centre in this case, there are No pre-defined set of stock
break-up of each transaction as well as details of groups.
transaction for each cost centre. A Profit and Loss
• Second, you create the individual stock items, which
Statement of every cost centre can also be obtained.
is similar to setting up the ledgers.
Cost Centre Reports : These are the following reports - • Finally, you are ready to use vouchers to record the
various stock transaction.
Category Summary : This report displays the summary
The Inventory features comprises of configurations/
of all the cost centers under a cost category.
functionality pertaining to Inventory transactions and
reports. The Inventory features are further sub-divided into
Cost Centre Break-up: This report displays Ledger and
seven sections:
Group summary information for the selected cost centre.

170 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.124

Copyright Free under CC BY Licence


General 4 Stock Transfers : Stock transfer report display entries
made using stock journal vouchers.
Storage & Classification
5 Physical Stock Register : Physical stock register is
used to record actual stock available, i. e. Stock found
Order Processing
on conducting a stock check. It is not unusual to find a
Invoicing discrepancy between the actual stock and the computer
recorded stock figure. If inventory vouchers have been
Purchase Management configured to ignore physical stock differences, these
physical stock vouchers will be useful for recording
Sales Management purposes.

Other Features Statements of Inventory : There are Godown, stock


categories, stock query, reorder status, purchase bills
Inventory Reports : Tally generates inventory reports pending, sales bills pending.
based on vouchers entries made. You can use the
customised reports to compare inventory data between 1 Godown : A place where stock items are stored is
different companies, periods of the financial year and so referred to as Godowns. You can specify where the
on. There are Inventory Books and Statements of Inventory. stock items are kept, e.g. warehouse, shelf or rack,
etc, and obtain stock reports for each Godown, and
Inventory Books : In inventory books there are stock item, account for movement of stock between locations/
group summary, stock transfers, physical stock register. Godowns.
2 Stock Categories : This is a feature, which offers a
1 Stock Items : Stock item refers to goods in which you parallel classification of stock items. Like Stock Groups,
deal-that is, goods that you manufacture or trade(sell classification is done based on some similar behavior.
and purchase). It is the primary inventory entity. Similar The advantage of categorizing items that Tally allows
to ledgers being used in accounting transactions - you you to classify stock items (based on functionality)
have to use Stock Item in Inventory transactions. together - across different stock groups, enabling you
Therefore, Stock Items are important in Inventory like to obtain reports on alternatives or substitutes for a
how Ledgers are important in Accounting. stock item.
2 Units of Measure : Stock items are mainly purchased 3 Stock Query : Stock query allows you to obtain all
and sold on the basis of quantity. The quantity is information about a stock item. It displays all the
measured by units. In such a case, it is necessary to necessary real time information about an item that you
create the unit of measure. Units of measure can be may require to help negotiate order with a customer on
simple units such as nos., meters, kilograms, pieces, a single screen. It also display cost and price details
or compound units, e.g. box of 10 pieces. Create the of alternative items.
units of measure before creating the stock items.
4 Purchase Bills Pending : Purchase bills pending
displays all instance of incomplete purchases where
3 Stock Groups : Similar to Groups in Accounting goods may have been received, but not fully invoiced.
Masters - these are provided for the purpose of It also displays instances of invoices received, but
classification of stock items. Classification is done goods have not been received.
based on some common behavior. Grouping stock items 5 Sales Bills Pending : Sales bills pending displays all
enables easy identification and reporting of stock items instance of incomplete sales where goods may have
in Statements. The group summary statement shows been delivered, but not fully invoiced. It also displays
the closing balances of accounts under the selected instances of invoices raised, but goods have not been
group upto the current date. For example, items of a
delivered.
particular brand can be grouped together so that you
can get the inventory details of all items of that brand.
It is NOT necessary to group items.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.124 171

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.3.125 & 2.3.126
COPA - Using Accounting Software

Budgeting systems, Scenario management and Variance analysis


Objectives: At the end of this lesson you shall be able to
• understand the meaning of budget & budget manual
• know the budget period, classification of budgets and its types
• understand scenario management
• understand variance analysis.

Introduction : Planning has become the primary function 1 Budget controller : The chief executive is ultimately
of management these days. Budgets are nothing but the responsible for the budget programme. But large part of
expressions, largely in financial terms of management’s the supervisory responsibility is deligated to an official
plan for operating and financing the enterprise during designated as budget controller or budget director. The
specific periods of time. budget controller should have knowledge of the techni-
cal side of the business and should report direct to the
A budget is a detailed plan of operations for some specific president of the organisation.
future period. It is an estimate prepared in advance of the
2 Budget committee : The Budget controller will be
period to which it applies. It acts as a business barometer
assisted in his work by the Budget committee. The
as it is complete programme of activities of the business for
budget committee will consists of heads of the various
the period covered.
departments as production, sales, finance, etc., Budget
controller is the chairman of the committee. It will be the
Essentials of a Budget
duty of the budget committee to submit, discuss and
a It is prepared in advance and is based on a future plan finally approve of the budget figures. Each Head of the
of actions Department will have his own sub-committee with
b It relates to a future period and is based on objectives executive working under him as in members.
to be attained
Fixation of the Budget Period : Budget period means
c It is a statement expressed in monetary and / or the period for which a budget is prepared and employed.
physical units prepared for the implementation of policy
formulated by the management. The budget period will depend upon the following:

Budget manual : The budget manual is a written docu- 1 The nature of the business and
ment or booklet which specifies the objectives of the
2 The control techniques to be applied
budgeting organization and procedures.
For example, a seasonal industry will budget for each
The following are the important matters covered in a budget
season. An industry requiring long periods to complete
manual
work will budget for 3 or 4 or 5 years. But Budget period
should not be longer than that of what is necessary.
1 A statement regarding the objectives of the organisa-
tion and how they can be achieved through budgetary
Budget Procedure
control.
2 A statement regarding the functions and responsibili- Determination of key factor : Key factor indicates whose
ties of each executive regarding preparation of budget influence must first be assessed in order to ensure the
and execution of budget. accomplishment of the functional budgets. Functional
budget is related to different functions of a business, e.g.,
3 Procedures to be followed for obtaining the necessary
sales, production, purchases, cash, etc.,
approval of budgets.
4 Time table for all stages of budgeting. The budget related to the key factor should be prepared
first. Then the other budgets.
5 Reports, statements, forms and other records to be
maintained.
General list of key factors in different industries are given
6 The accounts classification is to be employed. below:

Responsibility for Budgeting : There are two things Industry Key factor
responsible for budgeting. They are the budget controller
1 Motor car Sales demand
and the budget committee.
2 Aluminium power

172

Copyright Free under CC BY Licence


3 Petrolium Refinery Supply of crudeoil d Purchase Budget : This budget forecasts the quantity,
and value of purchases required for production. It gives
4 Electro optics Skilled technicians
quantity -wise, money-wise and period - wise informa-
5 Hydral power generation Monsoon tion about the materials to be purchased

Making of forecasts : A forecast is the statement of facts e Personnel Budget : This budget anticipates the quan-
likely to occur that may affect the flow of budget. Forecast tity of personnel required during a period for production
is done before the budgeting starts. Forecasts are made activity
regarding sales, production cost and financial require- f Research Budget : This budget relates to the research
ments of the business. works for improvement in quality of products or research
for new products.
Consideration of alternative combination of forecasts:
g Capital Expenditure Budget : This budget provides a
Alternative combinations of forecasts are considered with
guidance regarding the amount of capital that may be
a view to obtain the most efficient overall plan so as to
required for procurement of capital assets during the
achieve maximum profit.
budget period
Preparation of Budgets : After finalising the forecasts, h Cash Budget : This budget forecasts the cash position
the actual budgets will be prepared. One budget may be by time period for a specific duration of time
prepared on the basis of the other budget. For example
i Master Budget : This is a summary budget incorporat-
production budget will be prepared on the basis of the sales
ing all functional budgets in a capsule form.
budget.
Flexibility based Budget
Classification of Budgets
a Fixed Budget : A budget prepared on the basis of a
Budgets can be classified into three most common types
standard or a fixed level of activity is called a fixed
1 Time based Budget budget. It does not change with the change in the level
2 Function based budget of activity

3 Flexibility based budget b Flexible Budget : A budget designed in a manner so


as to give the budgeted cost of any level of activity is
Time based budget : In terms of time, the budget can termed as a flexible budget.
broadly be classified into four categories
Accounting Features : The Accounting Features con-
a Long term Budget : A budget designed for a long sists of configurations / functionality, which generally
period is termed as long term budget. The period may affects accounting transactions and reports. The account-
be from 5 to 10 years ing features are further sub-divided into six sections,
namely:
b Short term budget : A budget designed for a period
generally not exceeding 5 years is termed as short term General
budget
Out standings Management
c Current budgets : A budget which is prepared for a
very short period, say a month or a quarter is termed as Cost /Profit Centers Management
current budget Invoicing
d Rolling Budgets : A budget which is designed for a Budgets / Scenario Management
year in advance is termed as Rolling Budgets or
Progressive Budgets Other Features

Function Based Budget Scenario Management: This is a management tool


which displays of accounts and inventory related informa-
a Sales Budget : This budget forecasts total sales in tion, by selectively including certain types of vouchers. It is
terms of quantity, value, items, periods, area, etc., a forecasting tool which forecast the expenses using
b Production Budget : This budget is based on sales provisional Vouchers and includes them in the reports.
budget. It forecasts quantity of production in terms of
Scenario Analysis : Scenario planning is also called
items, periods, areas, etc.,
scenario analysis. It is a strategic planning method that
c Cost of Production budget : This budget forecasts the some company use to make flexible long-term plans. Thus
cost of production, separate budgets are prepared for the scenario analysis is process of analyzing possible
different elements of costs. future events by considering alternative possible out-
comes.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.125 & 2.3.126 173

Copyright Free under CC BY Licence


Several Scenarios are demonstrated in a scenario analysis standard amount and the actual amount incurred/sold.
to show possible future outcomes. It is useful to generate Variance analysis is usually associated with explaining
a combination of an optimistic, a pessimistic and a most the difference (or variance) between actual costs and the
likely scenario. standard costs allowed for the good output. For example,
the difference in materials costs can be divided into a
Variances : Variances can be computed for both costs materials price variance and a materials usage variance.
and revenues. The difference between the actual direct labor costs and
the standard direct labor costs can be divided into a rate
The concept of variance is connected with planned and variance and an efficiency variance. The difference in
actual results. It is effect to the difference between those manufacturing overhead can be divided into spending,
two on the performance of the company. efficiency, and volume variances. Mix and yield variances
can also be calculated.
Variance Analysis : Variance analysis is a tool of budg-
etary control by evaluation of performance by means of Variance analysis helps the management to understand
variances between budgeted amount, planned amount or the present costs and thereafter control the future costs.

174 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.125 & 2.3.126

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.3.127 & 2.3.128
COPA - Using Accounting Software

Concepts of Ratios, Analysis of financial statements


Objectives: At the end of this lesson you shall be able to
• understand the concept of stock
• understand ratio analysis
• understand cash flow
• understand fund flow accounting
• explain the invoice.

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

750 Total 8,175

175

Copyright Free under CC BY Licence


Unit cost = 8,175 2 Sales made during these two weeks amounted to
Rs.3000. The firm makes a gross profit of 33 1/3% on
750
sales. Find out the value of closing stock on 30th June,
= 10.90 2001.

The value of 300 units = 300 x 10.90 For this case the statement of stock can be calculated as
under:
= Rs. 3,270
Statement of stock
Base Stock Method : In this method, the minimum stock
carried by the factory is valued at the price originally paid Stock on 30th June 2001
for it. The excess of actual stock over the minimum level is
Rs.
valued according to the current cost, calculated in one of
the three methods given above. Sales 3,000
Less 33 1/3% on sales 1,000
Suppose the minimum stock is 200 units and the original
price paid was Rs.8 per unit. Sales at cost 2,000
Value of stock two weeks after 22,500
The value of stock of 200 units @ Rs.8 = Rs.1,600
30th June 2001
The value of remaining 100 units is calculated with the unit
Less:purchases during 2 weeks 500
price of Rs.11.50 or Rs.11.00 or 10.83 or 10.90
Value of stock on 30th June 2001 22,000
Statement of stock : M/s. Nanda & Bose close their
financial books on 30th June 2001. Stock taking continues
for two weeks after this date. In 2001, the value of stock Inventory control and Reordering : Inventory control
came to Rs.20,500, without making adjustments for the system always monitors the availability of stock. In any
following:- business minimum stock should be maintained for
uninterupted sale. If the minimum stock level falls, then the
1 Purchases made during the two weeks after 30th June purchase order for that product is to be made.
2001 were Rs.500
The minimum stock level below which purchase order is to
be made is known as reorderlevel. If the stock level falls
below the reorder level purchase order is proposed.

Example

Item No. Description Stock Reorder Reorder


level yes/no

10283 REXONA BIG 125 50 N


10284 REXONA SMALL 25 50 Y
10285 CINTHOL NEW 85 75 N
10286 CINTHOL OLD 15 25 Y
10287 VICCO PASTE 100 10 15 Y
10288 VICCO PASTE 50 00 15 Y
10289 VICCOTURMERIC 15 27 N

Purchase order should be made for the items 10284, In Accounting, there are many standard ratios used to try
10286, 10287, 10288. Hence the purchase order can be to evaluate the overall financial condition of a corporation or
proposed using the inventory control system. other organization. It are also compared across different
companies in the same sector to see how they stack up,
Ratio Analysis : Ratio Analysis is used to evaluate various and to get an idea of comparative valuations.
aspects of a company's operating and financial perform-
ance such as its efficiency, liquidity, profitability and Types of Ratios :
solvency.
1 Financial Ratios : These are categorized according to
the financial aspect of the business which the ratio

176 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.127 & 2.3.128

Copyright Free under CC BY Licence


measures. It allow for comparisons between compa- Fund Flow Accounting : These statements give the
nies, between industries, between different time peri- information of funds on a particular date. The purpose of
ods for one company, between a single company and preparation of funds flow statements is to know about from
its industry average. where funds are coming and where being invested. The fund
flow stalemates is generally prepared from the data iden-
2 Liquidity Ratios : It is measure that the availability of
tifiable and profit and loss account and balance sheets.
cash to pay debt.
Fund Flow statement is also called as sources and
3 Activity Ratios : It is measure how to quickly a firm application of funds. It shows the detail of funds business
converts non-cash assets to cash assets. received from sources and the amount of funds the busi-
4 Debt Ratios : It is measure the firm's ability to repay ness used for different purpose in the year.
long-term debt.
Invoice : While making a sale, the seller prepares a
5 Profitability Ratios : It is measure the firm's use of its statement giving the particulars such as the quantity, price
assets and control of its expenses to generate an per unit, the total amount payable, any deductions made
acceptable rate of return. and shows the net amount payable by the buyer. Such a
6 Market Ratios : It is measure the investor response to statement is called invoice.
owning a company's stock and also the cost of issuing
An invoice is a statement of list of goods with their quantity
stock.
and price.
Cash Flow Accounting : In accounting cash flow is the
An invoice is a business document which is prepared by
difference between the amount of cash available at the
sellers and given to buyers. Usually the invoice are pre-
opening balance (beginning of a period) and the amount at
pared in triplicate one copy will be issued to the buyer. The
the closing balance (end of that period).
after two copies will be retained by the seller.
When Cash is coming in from customers or clients who are
Inward Invoice : To the buyer, he calls the invoice as
buying your products is called accounts receivable and
'inward invoice'. He enters the details of the invoice in his
when the cash is going out of your business in the form of
purchase book.
payments for expenses like rent, loan payment is called
accounts payable.
Outward Invoice : To the seller, he calls the invoice as
'outward invoice'. He enters the details of the invoice in his
The net cash flow of a company over a period is equal to the
sales book.
change in cash balance over this period : positive if the cash
balance increases, negative if the cash balance decreases.
Details of the Invoice : The invoice should give the
The total net cash flow is the sum of cash flows that are
following details:
classified in three areas:
1 Name and address of the seller
1 Operational Cash Flows : Cash received or expended
as a result of the company's internal business activi- 2 Name and address of the buyer
ties. It includes cash earnings plus changes to working
3 Invoice Number
capital.
4 The Date
2 Investment Cash Flows : Cash received from the sale
of long-life assets, or spent on capital expenditure. 5 Quantity, description, unit price, amount of the goods
sold
3 Financing Cash Flows : Cash received from the issue
of debt and equity, or paid out as dividends, share 6 Trade discount and cash discount, if necessary
repurchases or debt repayments. 7 Expenditure
In financial accounting, a cash flow statement is also 8 Net amount
known as statement of cash flows which is a financial 9 Signature of the invoicing authority
statement that shows how changes in balance sheet
accounts and income affect cash and cash equivalents, 10 E. & O. E. at the left bottom corner of the invoice
and breaks the analysis down to operating, investing and
financing activities. The cash flow statement is concerned E. & O. E. means Errors and Omission Excepted. This
with the flow of cash in and out of the business. indicates that if errors and omissions are found out, the
matter can be reported and settled and the seller under
takes to correct them.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.127 & 2.3.128 177

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.3.129
COPA - Using Accounting Software

Tax processing in Tally


Objectives: At the end of this lesson you shall be able to
• explain statutory & taxation
• explain direct & indirect taxes
• explain VAT & service tax processing
• explain TDS, TCS, FBT taxes
• explain GST.
Statutory & Taxation : The Statutory & Taxation features The buyer files the TDS returns containing details of the
comprises of configurations/functionality pertaining to seller and the bank, where the Tax Deducted at Source
statutory compliances available in Tally.ERP9. The amount is deposited to the Income Tax Department.
Statutory features are country specific and strictly depends
upon the Country selected in the Company Creation Tax Collected at Source : Tax Collected at Source (TCS)
screen. The following features are available, when India is is income tax collected by seller in India from payer on
selected in the Statutory Compliance for field in the sale of certain items. The seller has to collect tax at
Company Creation screen. specified rates from the payer who has purchased these
items :
• Excise
• Alcoholic liquor for human consumption
• Value Added Tax
• Tendu leaves
• Service Tax
• Timber obtained under a forest lease
• Tax Deducted at Source
• Timber obtained by any mode other than under a forest
• Tax Collected at Source
lease
• Payroll
• Any other forest produce not being timber or tendu
• Income Tax leaves
• GST • Scrap
• Parking lot
Tax : The Tax is a financial charge upon an individual
(called taxpayer) by a country / state or the functional • Toll plaza
equivalent of a state such that failure to pay, is punishable
• Mining and quarrying
by law.
The TCS on the above mentioned items vary from 1% to
Taxes are two types : direct or indirect taxes.
5%.
Direct Taxes : Direct Taxes are taxes collected by
FBT : Fringe Benefits Tax (FBT) is taxation of most which
government, directly from tax payers, through levies such
are generally non-cash employee benefits. A new tax was
as income tax, wealth tax and interest tax. In the case of
imposed on employers by India's Finance Act 2005 was
direct taxes, the incidence and burden of paying the tax
introduced for the financial year commencing April 1, 2005.
falls on the same person.
The fringe benefit tax was temporarily suspended in the
2009 Union budget of India by Finance Minister Pranab
TDS : Tax Deducted at Source (TDS) is one of the modes
Mukherjee.
of collecting income tax in india. The buyer (deductor)
deducts the tax from the payment made to the seller
The following items were covered:
(deductee) and remits the tax to the Income Tax
Department within the stipulated time.
• Employer's expenses on entertainment, travel,
employee welfare and accommodation. The definition
The buyers (Corporate and Non-Corporate) make payments
of fringe benefits that have become taxable has been
(such as Salary, Rent, Dividends, Professional Fees,
significantly extended. The law provides an exact list
Commission, etc) to the sellers (Services) and deduct the
of taxable items.
requisite amount from such payments towards tax.
• Employer's provision of employee transportation to work
These taxes are on Immovable Property, Contractor, Rent or a cash allowances for this purpose.
of Machinery, Rent of Land and Building.
• Employer's contributions to an approved retirement plan
(called a superannuation fund).

178

Copyright Free under CC BY Licence


• Employee stock option plans (ESOPs) have also been Invoice
brought under fringe benefits tax from the fiscal year
2007-08. Rule 4A prescribes that taxable services shall be provided
and input credit shall be distributed only on the basis of a
Indirect Taxes : Indirect Tax, imposed on commodities, bill, invoice or challan. Such bill, invoice or challan will
is indirectly borne by the people. It includes value added also include documents used by service providers of
tax, sales tax, customs duty, excise duty. In the case of banking services (such as pay-in-slip, debit credit advice
indirect taxes, the person on whom the incidence to pay etc.) and consignment note issued by goods transport
the tax falls is different from the person who carries the agencies. Rule 4B provides for issuance of a consignment
burden of paying the tax. note to a customer by the service provider in respect of
goods transport booking services.
Service Tax
Value Added Tax : The Government of India has, after
Service Tax is a tax imposed by Government of India on committing to the World Trade Organization regime,
services provided in India. The service provider collects decided to modernize and streamline its indirect taxation,
the tax and pays the same to the government. It is charged in the light of the experience of other WTO member
on all services except the services covered in the negative countries. The Government has availed of the services of
list (Section 66d of Finance Act'1994) of services & services the international management consulting firm for drafting
covered under Mega Exemption Notification (Notification of rules, procedures and forms for introduction of VAT. VAT
NO. 25/2012 ST dated 20.06.2012). The current rate is is prevalent in over 140 countries including India.
12.36% on gross value of the service. Introduction of VAT would be a historic reform of the
domestic trade tax system. It is expected to facilitate the
Dr.Raja chelliah committee on tax reforms recommend states and union territories to transit successfully from
the introduction of service tax. Service tax had been first the erstwhile sales tax system to modern domestic system.
levied at a rate of five per cent flat from 15 July 1994 till 13
May 2003, at the rate of eight percent flat w.e.f 1 plus an A Value Added Tax (VAT) is applies the equivalent of a
education cess of 2% thereon w.e.f 10 September 2004 le sales tax to every operation that creates value. The example
services provided by service providers. The rate of service is a Toy manufacturer company imported plastic. That
tax was enhanced to 12% by Finance Act, 2006 w.e.f company will pay the VAT on the purchase price, remitting
18.4.2006. Finance Act, 2007 has imposed a new that amount to the government. The company will then
secondary and higher education cess of one percent on use the plastic into a toy, selling the toy for a higher price
the service tax w.e.f 11.5.2007, increasing the total to a wholesale distributor. The company will collect the
education cess to three percent and a total levy of 12.36 VAT on the higher price, but will remit to the government
percent. The revenue from the service tax to the only the excess related to the "value added". The wholesale
Government of India have shown a steady rise since its distributor will then continue the process, charging the
inception in 1994. The tax collections have grown retail distributor the VAT on the entire price to the retailer,
substantially since 1994-95 i.e. from Rs. 410 crores in but remitting only the amount related to the distribution
1994-95 to Rs.132518 crores in 2012-13. The total number mark-up to the government. The last VAT amount is paid
of Taxable services also increased from 3 in 1994 to 119 in by the retail customer who cannot recover any of the
2012. However, from 1 July 2012 the concept of taxation previously paid VAT. For a VAT and Sales Tax of identical
on services was changed from a 'Selected service approach' rates, the total tax paid is the same, but it is paid at differing
to a 'Negative List regime'. This changed the taxation points in the process.
system of services from tax on some Selected services to
tax being levied on the every service other than services VAT is usually administrated by requiring the company to
mentioned in Negative list. complete a VAT return, giving details of VAT it has been
charged (input tax) and VAT it has charged to others
Service Tax Return (output tax). The difference between output tax and input
tax is payable to the Local Tax Authority.
According to Rule 5 of Service Tax Rules, 1994, records
include computerized data and means the record as If input tax is greater than output tax the company can
maintained by an assessee in accordance with the various claim back money from the Local Tax Authority.
laws in force from time to time. Records maintained as
such shall be acceptable to Central Excise Officer. Every Mechanism of tax credit:
assessee is required to furnish to the Central Excise Officer
at the time of filing his return for the first time a list of all For the VAT auditors, the knowledge of tax credit is utmost
accounts maintained by the assessee in relation to Service important. Therefore it is necessary to understand the
Tax including memoranda received from his branch offices. mechanism of tax credit.
This intimation may be sent along with a covering letter
while filing the service tax return for the first time. WHAT is Tax Credit ?

1 It is a salient feature of VAT.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.129 179

Copyright Free under CC BY Licence


2 It is available to registered Purchasing Dealer. Tally.ERP 9 ensures you generate GST invoices and
transactions as per the GST format.
3 Availability of the credit of tax paid on purchases of
taxable goods.
Able to file GSTR-1, GSTR-3B and GSTR-4 on your own
4 Tax credit is available at the point of purchases. by exporting data to the Excel Offline Utility tool or in
JSON format as per the GST portal. The unique error
5 Purchases of goods should be intended for the specific
detection and correction capability ensures that you file
purposes.
returns accurately.
6 Original Tax Invoice is must stating separate amount
of tax charged. When it comes to e-Way Bills, Tally.ERP 9 helps you to
easily generate and manage e-Way Bills. You can capture
7 Tax credit is not dependent or related either sale of
all the required information at invoice level itself, export
very goods or it is used in manufacturing.
the data in JSON format and upload the data in the e-Way
8 Tax Credit is adjustable against payment of tax / liability portal to generate the e-Way Bill.
of tax.
In the year 2005, VAT was introduced to overcome
GST (Goods and Services Tax) cascading affect (tax on tax). While VAT did eliminate the
cascading tax effect on the indirect taxes within a state,
- Goods and Services Tax (GST) is an indirect tax levied the cascading effect of other indirect taxes across the
in India on the supply of goods and services. country, still remained. For example, the Central Sales
- GST has been introduced to replace multiple indirect Tax (CST) applicable on interstate trade was non-creditable,
taxes levied by State and Central Governments in order leading to a break in the input credit chain. Similarly, a
to simplify the indirect tax. manufacturer charging Excise Duty on sale to a dealer
caused the chain to break. This uncreditable tax found its
- GST is levied at every step in the production process, way into the product cost.
but is refunded to all parties in the chain of production
other than the final consumer. GST on the other hand, allows for seamless flow of tax
- GST is a comprehensive Value Added Tax (VAT) on credit, and eliminates the cascading effect of all indirect
goods and services. taxes across the supply chain from manufacturers to
retailers, and across state borders.
- France was the first country to introduce this system
in 1954. Today it has spread to over 140 countries. A quick comparison of the taxes one paid in the previous
- Comprehensive dual GST has been implemented in regime and in the current regime, will able to understand
India Since 1st July 2017. the aspect of GST vs VAT clearly.

GST means different things to different stakeholders. • Previous Regime-Taxes paid by the dealer (Excise)
Businesses registered as regular dealers need to file their to the manufacturer is added to the cost. When the
GSTR-1 on a monthly basis if their aggregate turnover dealer sells down the chain, VAT keeps getting charged
exceeds 1.5 Cr. Businesses with aggregate turnover less on the sum of actual product cost + excise component,
than 1.5 Cr have to do GSTR-1 return filing on a quarterly and the VAT keeps getting levied at every point of sale,
basis. Also, both the businesses need to file their GSTR- till it reaches the end customer.
3B on a monthly basis.
• GST Regime- Taxes paid by dealer (CGST + SGST)
On the other hand, composite dealers have to file GSTR- to manufacturer is not added to cost. This is because
4 on a quarterly basis. Also, going forward, as e-Way bill GST allows the dealer to set off the tax liability of CGST
becomes mandatory for interstate and intrastate + SGST. This is one of the fundamental features of
movement of goods worth Rs. 50,000/- GST, which allows seamless credit from manufacturer
to dealer, and eliminates the cascading effect of taxes.
Components of GST? At the 26th GST Council meeting, it has been decided to
implement he inter-state e-way bill from 1st April, 2018.
There are 3 taxes applicable under GST: CGST, SGST & For intra-state movement, the e-way bill will be rolled out
IGST. in a phased manner starting from 15th April, 2018, such
that all states are covered by 1st June, 2018.
CGST: Collected by the Central Government on an intra-
state sale (Eg: Within the same State) Eway bill - Introduction
SGST: Collected by the State Government on an intra- In its 22nd meeting, the GST Council decided and
state sale (Eg: Within the same State ) recommended that the e-way bill under GST shall be
introduced in a staggered manner from 1st January, 2018,
IGST: Collected by the Central Government for inter-state and will be rolled out nationwide from 1st April, 2018.
sale (Eg: one state to another state)

180 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.129

Copyright Free under CC BY Licence


However, at the recently concluded 24th GST Council If the recipient of goods doesn’t communicate acceptance
meeting held on 16th December, 2017, it was announced or rejection within 72 hours, it will be deemed as accepted
that the e-way bill will be launched from the 1st of February, by the recipient. The facility of generation and cancellation
2018 – a full two months ahead of the earlier plan. of E-Way Bill will be made available through SMS.

The GST Council, reviewed the readiness of the hardware HSN stands for Harmonized system of Nomenclature which
and software required for the nationwide rollout of e-way was developed by world customs organisations (WCO)
bill, and has announced the renewed date, post discussions with the vision of classifying goods all over the world in a
with all the States. systematic manner.

The E-Way Bill is applicable for any consignment value HSN Contains six digit uniform code that classifies
exceeding INR 50,000. Even in case of inward supply of 5000 + products and which is accepted world wide. HSN
goods from unregistered person, E-Way Bill is applicable. code describes the commodity/product.
The E-Way Bill needs to be generated before the
commencement of movement of goods. Form GST EWB- India has already been using HSN system in the central
01 is an E-Way Bill form. It contains Part A, where the excise and customs regime.
details of the goods are furnished, and Part B contains
vehicle number. For multiple Consignments the transporter Tax payers whose turnover is below Rs.1.5 crores are not
should generate a consolidated E-Way Bill in the Form required to mention HSN code in their invoices. The list of
GST EWB 02 and separately indicate the serial number HSN codes are available in public domain.
of E-Way Bill for each of the consignment.
The E-Way Bill format in GST comprises of 2 parts – Part
Upon generation of the E-Way Bill, on the common portal, A and Part B.
a unique E-Way Bill number called ‘EBN’ will be made
available to the supplier, the recipient and the transporter.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.129 181

Copyright Free under CC BY Licence


GST E-Way Bill Format A.7 : Reason for Transportation : The reason for
transportation is pre-defined and you need to select the
FORM GST EWB-01 most appropriate option from the list.

(See Rule 138) Code Description

E-Way Bill 1 Supply


2 Export or Import
PART A
3 Job Work
A.1 : GSTIN of Recipient : Mention the GSTIN number of
4 SKD or CKD
the recipient.
5 Recipient not known
A.2 : Place of Delivery : Mention the Pin Code of the
6 Line Sales
place where goods are delivered.
7 Sales Return
A.3 : Invoice or Challan Number : Mention the Invoice or
8 Exhibition or fairs
Challan number which the goods are supplied.
9 For own use
A.4 : Invoice or Challan Date : Mention the Invoice or
10 Others
Challan Date which the goods are supplied.
A.8 : Transport Document Number : This indicates either
A.5 : Value of Goods: Mention the consignment value of one of the Goods Receipt Number, Railway Receipt
goods. Number, Airway Bill Number or Bill of Lading Number.

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.

FORM GST EWB-02


(See Rule 138)

Consolidated EWay Bill

Number of EWay Bills: :

EWay Bill Number

182 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.129

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.3.130
COPA - Using Accounting Software

Utilities
Objectives: At the end of this lesson you shall be able to
• utilities in Tally
• split company data
• export master data
• import master, vouchers
• enable Tally vault password.

Utilities & Others @ Tally.ERP9

• Back Up / Restore

• Split Company Data

• Tally.ERP 9 Vault

• Exporting Master Data

• Importing Data

• Consolidation of Accounts

• Password or Security Control

• Enabling Cheque Printing

• Credit Limits

• Bills of Materials (BOM)

• Re-Order Levels and Re-Order Quantity

• Price Levels or Price List

• Interest Calculations

• Voucher Classes & Voucher Types (Creations)

• Point of Sale ( POS Invoicing )

Splitting Company Data based on Financial Years • The company data is verified to ensure that no errors
occur during splitting using the Verify Company Data
Prerequisites for splitting company data option.
Before splitting the data, the user must ensure that: To split the company data

• A backup of the data exists. 1 Go to Gateway of Tally > F3 : Cmp Info . > Split
Company Data > Select Company .
• All unadjusted forex gains/losses have been fully 2 Select the required company from the List of
adjusted by recording journal entries. Companies .
• No purchase/sales bills are due. Check the Profit & 3 Enter the required date in the Split from field.
Loss A/c and inventory statements (purchase/sales
bills pending). You have to account them in the
respective party accounts or in the bills pending
account.

183

Copyright Free under CC BY Licence


The Split Company Data screen appears as shown below: Fig 2
(Fig 1)

Fig 1

Importing Masters

Import masters previously exported from Tally.ERP 9 in


4 Press Enter to split the company data. XML format into the data of a company. Before importing,
ensure that all the same features are enabled and disabled
Important points to remember: in the Company Features as the company from which
the data is being imported.
• The Split from date is based on the existing data, and
is considered as the beginning of the current financial For example, if you want to import masters created in
year. ABC Company to a new company - XYZ Company. The
options Maintain stock categories and Maintain batch-
• Once the company data is split, two separate
wise details must be enabled in ABC company before
companies will be created and opened, without any
exported the masters. To import masters into XYZ
changes to the original data.
Company, you need to ensure that both the options
• After the split, all the companies act as separate Maintain stock categories and Maintain batch-wise
companies. You can make entries, display reports and, details are enabled in XYZ Company before importing.
alter any data in these companies.
To import masters
Export Data from Masters in Tally.ERP 9
1 Go to Gateway of Tally > Import Data > Masters .
To export masters
2 Enter the name of the .xml file to be imported, if the file
is located in the Tally.ERP 9 application folder.
1 Go to Gateway of Tally > Display > List of
Accounts.
Note: By default, the export location is the
2 Click E : Export to open the Export Report . Tally.ERP 9 installation folder, which is also the
default import location. Therefore, it is not
3 Press Backspace to configure the export options.
required to specify the file path during import.
4 Select the Language . If the path is other than the installation folder,
you must specify the exact location path, for
5 Select the Format .
example, C:\Export_Files\XML\Master.xml or
6 Enter the Export Location . C:\Export_Files\XML\DayBook.xml
7 Enter the Output File Name .
3 Select the Behaviour to define the method by which
8 Select the Type of Masters to be exported. the existing entries in the company will be treated.
9 Set the option Include dependent masters? to Yes .
The Import Masters screen appears as shown below:
10 Enable Export Closing Balances as Opening , if (Fig 3)
required. The Export Report screen appears as shown
below: (Fig 2) Fig 3

11 Press Enter to export.

The exported file is saved in the location specified.

4 Press Enter to import.

184 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.130

Copyright Free under CC BY Licence


Importing Vouchers 2 In the Change Tally Vault screen select the required
company from the List of Companies.
Importing vouchers from one company to another in
3 Enter the Password in the New Password field.
Tally.ERP 9 could be due to the following reasons:
Tally.ERP 9 displays the strength of the password
entered depending on the combination - Alphabets,
• Data corruption/loss.
Numbers and Special Characters.
• Migrating into a later release.
4 Re-enter the password to confirm in the Repeat New
• Importing data from third party. Password field.
To import vouchers 5 Accept to Change the Tally Vault password.

1 Go to Gateway of Tally > Import Data > Vouchers . 6 Tally.ERP 9 displays a message Created New
Company followed by the new Company Number, press
2 Enter the name of the .xml file to be imported, in the any key to return to Company Info menu.
Import Vouchers screen, as shown below: (Fig 4)
Once the company data is encrypted the Name of the
Fig 4
Company and Financial Year will not be visible in the Select
Company screen.

7 In the Company Info, press Select


8 The Select Company screen with the encrypted
company is displayed as shown in Fig 6.
Note : By default, the export location is the Fig 6
Tally.ERP 9 installation folder, which is also the
default import location. Therefore, it is not
required to specify the file path during import.
If the path is other than the installation folder,
you must specify the exact location path, for
example, C:\Export_Files\XML\Master.xml or
C:\Export_Files\XML\DayBook.xml
9 Select the encrypted company, Tally.ERP 9 will prompt
3 Press Enter to import.
the user to provide the TallyVault password. (Fig 7)
Enabling Tally Vault Fig 7

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.

1 Go to Gateway of Tally press F3 : Company Info >


Change TallyVault (Fig 5) 10 Provide the required password and the company data
is available for use in a readable format.
Fig 5
To enable Tally Vault while creating a new company, you
must provide the TallyVault password and repeat the
password, the new company created will be secured using
Tally Vault.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.130 185

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.3.131
COPA - Using Accounting Software

Creating Users, Backup and restore


Objectives: At the end of this lesson you shall be able to
• create users and passwords
• backup and restore data.

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

3 Select the required Security Level from the Security


List
4 Enter the user’s name in the Name of User field.
5 Enter the password in Password (if any) field. (Fig 2)

Fig 2

- The backup companies on disk screen appears


containing two main option source and destination
- Type the path of the company beside the source option
to specify the location from where you want to take.

To do Auto Backup In Tally ERP 9

Data on the computer is dangerous from different types


of threat and any data loss cannot be recovered hence
there is need to store date at a different location by
Backup & Restore data In Tally.erp 9 taking a backup.

Tally.erp 9 provides the mechanism of taking a back up To activate a backup option of auto backup
data from on store medium into another storage 1 Go to a gateway of Tally > Alt + F3: comp info > Alter
medium.You can take a backup on the local drive or in an and select company from the list.
external media.
186

Copyright Free under CC BY Licence


2 Company Alternation screen appears. To restore Auto Backup Data
3 Enable auto backup? set to Yes
1 Go to Gateway of Tally > ALt + F3: Comp info >Restore.
4 Accept the company
2 In destination, field type the path in which you want to
5 Press ESC to come on Gateway of Tally Screen restore the back up data.
6 GO to Gateway of tally F12: Configuration > Date 3 In source, field type the path: D:\autobackup.
Configuration
4 In auto Backup section list of auto, backup appears
7 In location of auto backup files type the path in which select company from the list.
path you want to get back up D:\autobackup
5 In backup version select the latest backup.
8 Accept the data configuration Screen.
9 Message appears that do you want to restart Tally for
the change to have effect press Y.
10 Now when you close the Company Tally take the
backup automatically.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.131 187

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.3.132
COPA - Using Accounting Software

Multilingual capability in Tally


Objectives: At the end of this lesson you shall be able to
• list of accounts/ledgers
• configuration in tally
• multilingual capability in tally.

List of Accounts : Tally.ERP9 gives great flexibility in list • E-Mailing : with this option you can configure the e-
of accounts which displays the list as groups in mailing facility.
alphabetical order. The groups are in bold and begin on
• Data Configuration : with this option you can configure
the extreme left. The sub-groups are also in bold and the
the path where the language, data and configuration
ledger accounts are in italic and in the lowest level. The
files reside.
report is drill down and if press the enter key and then it
display ledger Alteration (Secondary) screen through the • Advanced Configuration : with this option you can
ledger accounts. configure the Client / Server, ODBC, Connection, Log,
Tally.NET.
Configuration in Tally : Tally.ERP9 allows you to modify
• Licensing : with this option you can configure the
these when your requirements to change the configurations.
update, surrender, reset license.
In Configuration consists of the following menus. Multilingual Capability in tally : Tally.ERP9 allows you
to record, view, print information in any one of the 9 Indian
• General : with this option you can configure the language (like Hindi, Gujarati, Punjabi, Tamil, Telugu,
Country Details, Style of Names, Style of Dates. Marathi, Kannada, Malayalam and Bengali), besides few
international languages such as Arabic, Bahasa Indonesia,
• Numeric Symbols : with this option you can configure
Bahasa Malayu etc. Tally enables you to enter data in
the number styles.
one language and have it transliterated into different
• Accts / Inventory Info. : with this option you can languages.
configure the details in Accounts Masters and Inventory
Masters. Some others features :
• Voucher Entry : with this option you can configure the
• It is a user friendly.
vouchers entries in Accounting and Inventory Vouchers.
• It offers concurrent multilingual support.
• Invoice / Orders Entry : with this option you can
configure the invoice, delivery notes, sales & purchase • It maintain your books of accounts while the data is
orders. accepted, sorted, maintained, displayed and printed
in any one of the language.
• Payroll Configuration : with this option you can
configure the statutory details, passport details, • It generate bill, invoices, vouchers, ledgers, receipts,
contract details and deactivated employees. reports, purchase orders or delivery notes in the
language of your choice after entering data for in any
• Banking Configuration : with this option you can
one of the specified languages.
configure the settings related to Bank reconciliation
statement. • It has easy to use keyboards layouts - inscript and
• Printing : with this option you can configure the printing phonetic.
parameters of a voucher, invoice and statement layouts
before final printing.

188

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.4.133
COPA - E Commerce

E commerce scope and benefits


Objectives: At the end of this lesson you shall be able to
• define E-commerce
• explain difference between traditional commerce and E-commerce
• explain type, scope and benefit of E-commerce
• explain capabilities required and technology issue of E-commerce.

E Commerce: As per The Asssociate Chambers of Commerce and


Industry in India (ASSOCHAM), online shopping continues
E Commerce is the process of buying and selling products to rule the roost and will cross Rs 10,000 crore mark which
or service and transfer of funds electronically. is 350 per cent more than last year's volumes.
Traditional Commerce Vs. E Commerce:
Electronic commerce draws on technologies such as
mobile commerce, electronic funds transfer, supply chain In traditional commerce the buyer has to go to a shop to
management, Internet marketing, online transaction buy a product or service, but in E commerce, the product
processing, electronic data interchange (EDI), inventory or services are listed in a web site and the buyer chooses
management systems, and automated data collection the product by verifying its photos and other specifications
systems. Modern electronic commerce typically uses the given in the web sites and then paying the price preferably
World Wide Web for at least one part of the transaction's electronically by debit/credit card or Internet banking
life cycle, although it may also use other technologies method. Then the product is delivered to the customer
such as e-mail. address by the company. Delivery charge may be free or
it may be paid along with the payment of product cost.
E-commerce businesses usually employ some or all of
the following practices: In traditional Commerce the customer can physically verify
the product for example if someone is buying an LED TV
Provide Etail or "virtual storefronts" on websites with online can go to a shop and personally verify the picture quality
catalogs, sometimes gathered into a "virtual mall". himself/herself, but in e commerce website it is not
possible. Only buyer can see the photos of the product
Buy or sell on websites or online market places. but cannot watch the picture quality or sound quality by
himself/herself.
Gather and use demographic data through web contacts
and social media. In e commerce, the customer can save his time and money
by not going to the shop physically. But the customer
Use electronic data interchange, the business-to-business needs an Internet connection and device to buy products.
exchange of data.
In traditional commerce the buyer can physically meet
Reach prospective and established customers by e-mail the seller so if after sale service is required, the buyer can
or fax (for example, with newsletters). contact the seller but in e commerce the buyer does not
get the chance to physically meet the seller. So after sale
Use business-to-business buying and selling. service is to be arranged by customer by contacting the
service centers of respective product.
Provide secure business transactions.
The product prices are also a factor in traditional commerce
Flipkart's Big Billion Day sale on October 6, 2014 was as products should be stored in shops and employees
touted as the mother of all online sales, but on the big are also recruited to run the shop, the price goes high as
day, things went awry and customers were left feeling high there are rent for shop or it has to be owned the seller. In
and dry. While the founders promptly apologised about e commerce products are not transported to shop so the
the fact that they were not adequately prepared, the fact overhead of maintaining a shop is not added to the product
remains that ours is a nation that is latching on to e- cost. So products are cheaper in e commerce sites.
commerce in a big way.
Though there are few people who can get benefit from e
A single incident like this will not do much to dampen the commerce sites. Mostly who stay in urban areas gets
interest in the $ 3 billion sector that is poised for explosive benefit. Because the service it normally restricted to urban
growth. Already competitors of Flipkart such as Amazon areas only as villagers are not well equipped to use internet
and Snapdeal have learnt from this experience and probably enabled devices and making online transactions. That's
try not to repeat such incidents in future. why e commerce sites first checks buyers pin code number
to verify whether the product can be shipped to buyer or
not.
189

Copyright Free under CC BY Licence


With the advancement of technology in future this service • E Commerce is ideal for niche products. Customers
can be availed by all over the country. for such products are usually few. But in the vast market
place i.e. the Internet, even niche products could
With the advent of e commerce sites like filpkart, amazon generate viable volumes.
etc. traditional shop has seen a fall in sell as most urban
• Another important benefit of E Commerce is that it is
buyer now preferring e commerce sites to buy products
the cheapest means of doing business.
as they can buy product by sitting in the comfort of their
home. • The day-to-day pressures of the market place have
played their part in reducing the opportunities for
The customer can get the opportunity to see more products companies to invest in improving their competitive
in e commerce sites than in shop. So the option is more position. A mature market, increased competitions have
and e commerce sites also supply the product to the all reduced the amount of money available to invest. If
buyers home which shops normally does not do. the selling price cannot be increased and the
manufactured cost cannot be decreased then the
Type of E Commerce and its Scope: difference can be in the way the business is carried
out. Ecommerce has provided the solution by
E-commerce can be divided into four categories, which decreasing the costs, which are incurred.
are business to business b2b, business to customer b2c,
government to business g2b and government to citizen • From the buyer's perspective also ecommerce offers a
g2c. lot of tangible advantages.

There are four main areas in which companies conduct E- 1 Reduction in buyer's sorting out time.
commerce these areas are: 2 Better buyer descisions.

• Direct marketing, selling, and service. 3 Less time is spent in resolving invoice and order
discrepancies.
• Online banking and billing.
4 Increased opportunities for buying alternative
• Secure distribution of information. products.
• Value chain trading and corporate purchasing.
• The strategic benefit of making a business 'E Commerce
• Filling tax return to government. enabled', is that it helps reduce the delivery time, labour
cost and the cost incurred in the following areas:
The field of E-Commerce is very broad. There are many
applications of E-Commerce such as home banking, 1 Document preparation
shopping in electronic malls, buying stocks, finding a job, 2 Error detection and correction
conducting an auction, collaborating electronically with
business partners around the globe, and providing customer 3 Reconciliation
service. The implementation of various E-Commerce 4 Mail preparation
applications depends on four major support categories such
5 Telephone calling
as people, public policy, and marketing/advertising and
supply chain logistics. In addition there has to be an 6 Credit card machines
Infrastructure support. The E-Commerce management
7 Data entry
within each organization co-ordinates the applications and
infrastructure. In order to explain the relationships I have 8 Overtime
explained below the applications in the case of B2C E-
9 Supervision expenses
Commerce.
• Operational benefits of e commerce include reducing
Benefits of E Commerce:
both the time and personnel required to complete
business processes, and reducing strain on other
• E Commerce allows people to carry out businesses
resources. It's because of all these advantages that
without the barriers of time or distance. One can log
one can harness the power of ecommerce and convert
on to the Internet at any point of time, be it day or night
a business to E Business by using powerful E
and purchase or sell anything one desires at a single
Commerce solutions made available by E Business
click of the mouse.
solution providers.
• The direct cost-of-sale for an order taken from a web
site is lower than through traditional means (retail, paper Technology Requirements for E Commerce
based), as there is no human interaction during the
The requirements for E Commerce needs Web based
on-line electronic purchase order process. Also,
application with an HTML front end compatible with a variety
electronic selling virtually eliminates processing errors,
of browsers. The application will require a database to
as well as being faster and more convenient for the
store user transactions (such as items ordered by the
visitor.
user) and to list items available through the electronic store.
190 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.133

Copyright Free under CC BY Licence


The application must also include a middle tier-the Web Middle Tier
server and scripts executed by the server-to process
requests sent from Web browsers. A Web browser will The middle tier produces run time HTML output by
send HTTP requests to the middle tier. The middle tier will generating data in the middle tier itself or by retrieving
then retrieve information stored in the database, process data from the database. For example, in order to display a
it appropriately, and send a reply back to the client. list of items offered on a site, the middle tier would return
(Fig 1) the required information from the database, manipulate it
appropriately, then dynamically generate an HTML
Fig 1 document that displays the items of interest.

Options for implementing the middle tier include:

CGI (Common Gateway Interface) programs written in Perl


or C. These CGI programs access the database using the
database language APIs.

Another way is Servlets on the middle tier. Servlets access


the database by employing Java database APIs and the
Database JDBC database driver. (JDBC drivers are available for most
relational database management systems.)
An electronic database is utilized to store data associated
with E Commerce applications. Such information might Other options are Server-side scripting languages such
include information pertaining to registered users, goods as PHP or Perl. These languages support APIs for nearly
and services, and records of transactions effected by visitors all relational database management systems.
to the site.
Client Tier
We have two alternatives for storing this information:
The user interface comes under client tier. The user
• Employing flat files to store the data in text files. interface is designed by the dynamic middle tier programs
like PHP. So client gets web page as per his/her needs.
• Utilizing a relational database system such as MySQL, For example, some client may want to buy LED TV with
Oracle or SQL Server. 32" size. So the page can filter to show only 32" size TVs
to the client filtering others.
Flat files are strongly discouraged because they require
excessive development. Such development might entail Consider the sequence of actions performed by typical
designing layouts for data storage in text files so that data Internet users for buying a product:
may be manipulated, and designing simple interfaces to
access data stored in these files. • New users arriving at an eCommerce site for the first
time may create accounts. Existing users may
This functionality is readily available in relational databases. authenticate themselves by providing their unique
MySQL is an open source relational database, and, thus, identifiers and passwords.
has a significant cost advantage over other commercially
available relational database management systems. • After successful authentication, users may add items
they are interested in purchasing to their shopping carts
MySQL is highly scalable and is not difficult to administer. and view the list of items in their carts. (Of course,
A trained database administrator is not required to manage users may also wish to simply browse the electronic
MySQL installation, and management is relatively simple. store without purchasing items.)
• When viewing shopping cart contents, users may wish
MySQL supports client APIs for a variety of programming to change the quantities of items they have selected.
languages (such as Perl, C and PHP), and client programs
that access database information may be developed with • Site visitors may then checkout by confirming they
such APIs. We are, therefore, provided more programming would like to purchase the items in their shopping carts.
language choices for implementing the middle tier. The items in customers' shopping carts are then
entered into the database. Users may then continue
Oracle is also a very famous database package like My shopping or logout.
SQL but it is not open source. SQL Server is also not • Customers may also wish to return to the site at a
open source and developed by Microsoft. Any database later time to ascertain the shipping and delivery status
package may be used to storing database. of items they have purchased.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.133 191

Copyright Free under CC BY Licence


The flow chart below describes the typical interactions of
site visitors with the shopping cart application. (Fig 2)

Fig 2

192 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.133

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.4.134
COPA - E Commerce

Buidling Business on the Net


Objectives: At the end of this lesson you shall be able to
• explain different E-commerce sites
• explain online catalogues, shopping carts and check out pages
• explain payment, order processing and authorization, charge back
• explain other payment options.

Different E Commerce sites Internet Banking, Debit Card, Credit Card and various other
options. The buyer chooses the proper option for payment
Some of the world's most popular E Commerce sites are: and after successful payment, it is notified to the buyer
Crate & Barrel, Symantec, Amway, Microsoft, Amazon, and finally products are delivered to buyer address.
HP etc.
Authorization and chargeback
In India, after some initial hiccups, E Commerce is
gradually picking pace. Some of the popular web sites Authorization or authorization is the function of specifying
are: access rights to resources related to information security
and computer security in general and to access control in
Amazon, FlipKart, Jabong, Naaptol etc. particular.

On line catalogue, shopping carts and checkout Chargeback refers to paying the money back to the buyer
pages after the price has been deducted from his. It happens in
various situations. For an example, suppose someone buy
On line catalogues are list of products given on a web site a ticket in irctc web site and paid the price of the ticket
for sell. Buyer chooses the product by browsing through successfully, but later the ticket was not booked. Then
the products and choosing the product which suits him/ charge back will occur and the money would be refunded
her. back to the customer.

Shopping cart is a bucket full of products chosen by buyer Other payment options
before finally paying the price. It is used in retail stores
but the same concept has been implemented in Web site Apart from the above discussed payment option there are
by making a virtual bucket which shows the product some other ways for payment exists like mobile payment.
chosen by the buyer. Recently Airtel Money or Vodafone mpesa etc. mobile
payment methods has evolved so that, persons can pay
After choosing the desired product the buyer finally click by their mobile also.
checkout to pay the price for the products.
Various E Commerce transactions like paying utility bills,
Payment and order processing shopping from web sites, recharging etc can be done by
mobile.
After clicking checkout a payment option is shows which
normally has various options like COD (Cash on Delivery),

193

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.4.135
COPA - E Commerce

E-commerce Security issues and Payment Gateways


Objectives: At the end of this lesson you shall be able to
• explain E-commerce security issue
• explain payment gateway.

E Commerce security issue • Inability to access any web site


• Dramatic increase in the number of spam emails
E-commerce security is the protection of e-commerce
received.
assets from unauthorized access, use, alteration, or
destruction. While security features do not guarantee a
DoS attacks can be executed in a number of different
secure system, they are necessary to build a secure
ways including:
system.
ICMP Flood (Smurf Attack)
This massive increase in the uptake of eCommerce has
led to a new generation of associated security threats,
Where perpetrators will send large numbers of IP packets
but any eCommerce system must meet four integral
with the source address faked to appear to be the address
requirements:
of the victim. The network's bandwidth is quickly used up,
preventing legitimate packets from getting through to their
a Privacy - information exchanged must be kept from
destination.
unauthorized parties.
b Integrity - the exchanged information must not be Teardrop Attack
altered or tampered with.
A Teardrop attack involves sending mangled IP fragments
c Authentication - both sender and recipient must prove
with over lapping, over-sized, payloads to the target
their identities to each other and
machine. A bug in the TCP/IP fragmentation re-assembly
d Non-repudiation - proof is required that the exchanged code of various operating systems causes the fragments
information was indeed received. to be improperly handled, crashing them as a result of
this.
Security Threats
Phlashing
Technical attacks are one of the most challenging types
of security compromise an e-commerce provider must Also known as a Permanent denial-of-service (PDoS) is
face. Perpetrators of technical attacks, and in particular an attack that damages a system so badly that it requires
Denial-of-Service attacks, typically target sites or services replacement or reinstallation of hardware. Perpetrators
hosted on high-profile web servers such as banks, credit exploit security flaws in the remote management interfaces
card payment gateways, large online retailers and popular of the victim's hardware, be it routers, printers, or other
social networking sites. networking hardware. These flaws leave the door open for
an attacker to remotely 'update' the device firmware to a
Denial of Service Attacks modified, corrupt or defective firmware image, therefore
bricking the device and making it permanently unusable
Denial of Service (DoS) attacks consist of overwhelming a for its original purpose.
server, a network or a website in order to paralyze its
normal activity. Defending against DoS attacks is one of Distributed Denial-of-Service Attacks
the most challenging security problems on the Internet
today. A major difficulty in thwarting these attacks is to Distributed Denial of Service (DDoS) attacks are one of
trace the source of the attack, as they often use incorrect the greatest security fear for IT managers. In a matter of
or spoofed IP source addresses to disguise the true origin minutes, thousands of vulnerable computers can flood the
of the attack. victim website by choking legitimate traffic. A distributed
denial of service attack (DDoS) occurs when multiple
The United States Computer Emergency Readiness Team compromised systems flood the band width or resources
defines symptoms of denial-of-service attacks to include: of a targeted system, usually one or more web servers.
The most famous DDoS attacks occurred in February 2000
• Unusually slow network performance where websites including Yahoo, Buy.com, eBay, Amazon
and CNN were attacked and left unreachable for several
• Unavailability of a particular web site
hours each.

194

Copyright Free under CC BY Licence


Brute Force Attacks Another way to determine if a Web site is secure is to
look for a closed padlock displayed on the address bar of
A brute force attack is a method of defeating a your screen.
cryptographic scheme by trying a large number of
possibilities; for example, a large number of the possible If that lock is open, you should assume it is not a secure
keys in a key space in order to decrypt a message. Brute site. Of course, transmitting your data over secure channels
Force Attacks, although perceived to be low-tech in nature is of little value to you if the merchant stores the data
are not a thing of the past. unscrambled. You should try to find out if the merchant
stores the data in encrypted form. If a hacker is able to
Non-Technical Attacks intrude, it cannot obtain your credit data and other personal
information. Be sure to read the merchant's privacy and
Phishing is the criminally fraudulent process of attempting security policies to learn how it safeguards your personal
to acquire sensitive information such as usernames, data on its computers.
passwords and credit card details, by masquerading as a
trustworthy entity in an electronic communication. Phishing Research the Web Site before You Order
scams generally are carried out by emailing the victim
with a 'fraudulent' email from what purports to be a Do business with companies you already know. If the
legitimate organization requesting sensitive information. company is unfamiliar, do your homework before buying
When the victim follows the link embedded within the email their products. If you decide to buy something from an
they are brought to an elaborate and sophisticated unknown company, start out with an inexpensive order to
duplicate of the legitimate organizations website. Phishing learn if the company is trustworthy.
attacks generally target bank buyers, online auction sites
(such as eBay), online retailers (such as amazon) and Reliable companies should advertise their physical
services providers (such as PayPal). According to business address and at least one phone number, either
community banker, in more recent times cyber criminals buyer service or an order line. Call the phone number and
have got more sophisticated in the timing of their attacks ask questions to determine if the business is legitimate.
with them posing as charities in times of natural disaster. Even if you call after hours, many companies have a "live"
answering service, especially if they don't want to miss
Social Engineering-Social engineering is the art of orders. Ask how the merchant handles returned
manipulating people into performing actions or divulging merchandise and complaints. Find out if it offers full refunds
confidential information. Social engineering techniques or only store credits.
include pretexting (where the fraudster creates an invented
scenario to get the victim to divulge information), Interactive You can also research a company through the Better
voice recording (IVR) or phone phishing (where the fraudster Business Bureau, or a government consumer protection
gets the victim to divulge sensitive information over the agency like the district attorney's office or the Attorney
phone) and baiting with Trojans horses (where the fraudster General. Perhaps friends or family members who live in
'baits' the victim to load malware unto a system). Social the city listed can verify the validity of the company.
engineering has become a serious threat to e-commerce Remember, anyone can create a Web site.
security since it is difficult to detect and to combat as it
involves 'human' factors which cannot be patched akin to Payment gateways
hardware or software, albeit staff training and education A payment gateway is an e-commerce application service
can somewhat thwart the attack. provider service that authorizes credit card payments for
e-businesses, online retailers, bricks and clicks, or
How to be secure traditional brick and mortar.
Shop at Secure Web Sites
It is the equivalent of a physical point of sale terminal
located in most retail outlets. Payment gateways protect
Secure sites use encryption technology to transfer
credit card details by encrypting sensitive information, such
information from your computer to the online merchant's
as credit card numbers, to ensure that information is passed
computer. Encryption scrambles the information you send,
securely between the buyer and the merchant and also
such as your credit card number, in order to prevent
between merchant and the payment processor.
computer hackers from obtaining it en route. The only
people who can unscramble the code are those with A payment gateway facilitates the transfer of information
legitimate access privileges. Here's how you can tell when between a payment portal (such as a website, mobile
you are dealing with a secure site: phone or interactive voice response service) and the Front
End Processor or acquiring bank.
If you look at the top of your screen where the Web site
address is displayed (the "address bar"), you should see Transaction process
https://. The "s" that is displayed after "http" indicates
• When a buyer orders a product from a payment
that Web site is secure. Often, you do not see the "s"
gateway-enabled merchant, the payment gateway
until you actually move to the order page on the Web site.
performs a variety of tasks to process the transaction.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.135 195

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.5.136
COPA - Cyber Security

Overview of information security and threats


Objectives: At the end of this lesson you shall be able to
• describe information security and its basic principles
• describe the relation between information security and cybersecurity
• describe the key challenges in information security
• describe the benefits of information security
• explain the methods of implementing information security.

Introduction and availability - are also referred to as security attributes,


properties, security goals, fundamental aspects,
Information Security is the protection of information and information criteria, critical information characteristics and
information systems from unauthorized access, use, basic building blocks.
disclosure, disruption, modification, or destruction in order
to provide confidentiality, integrity, and availability. It is a Confidentiality
general term that can be used regardless of the form the
data may take (electronic, physical, etc.) Confidentiality is a set of rules that limits access to
information. Confidentiality prevents sensitive information
Governments, military, corporations, financial institutions, from reaching the wrong people, while making sure that
hospitals and private businesses storte a great deal of the right people can in fact get it. Protecting confidentiality
confidential information about their employees, customers, depends upon defining and enforcing appropriate access
products, research and financial status. Most of this levels for information. This may be done by separating
information is now collected, processed and stored on information into separate units organized by who should
electronic computers and transmitted across networks to have access to it and how sensitive it is.
other computers.
Integrity
If confidential information about a business' customers or
finances or new product line falls into the hands of a Integrity is the assurance that the information is
competitor or a hacker, a business and its customers could trustworthy, consistent and accurate over its entire life-
suffer widespread, irreparable financial loss, not to mention cycle. This means that data cannot be modified in an
damage to the company's reputation. Protecting unauthorized or undetected manner. Data must not be
confidential information is a business requirement and in changed in transit, and steps must be taken to ensure
many cases also an ethical and legal requirement. that data cannot be altered by unauthorized people (for
example, in a breach of confidentiality). In addition, some
Information assurance means must be in place to detect any changes in data
that might occur as a result of non-human-caused events
Information assurance is the act of ensuring that data is such as an electromagnetic pulse (EMP) or server crash.
not lost when critical issues arise. These issues include If an unexpected change occurs, a backup copy must be
but are not limited to: natural disasters, computer/server available to restore the affected data to its correct state.
malfunction, physical theft, or any other instance where
data has the potential of being lost. Since most information Availability
is stored on computers in our modern era, information
assurance is typically dealt with by IT security specialists. Availability is a guarantee of ready access to the
One of the most common methods of providing information information by authorized people. For any information
assurance is to have an off-site backup of the data in case system to serve its purpose, the information must be
one of the mentioned issues arise. available when it is needed. This means that the computing
systems used to store and process the information, the
Basic principles of Information Security security controls used to protect it, and the communication
channels used to access it must be functioning correctly.
The CIA Triad is a well-known model for security policy
development, used to identify problem areas and High availability systems aim to remain available at all
necessary solutions for information security. Confidentiality, times, preventing service disruptions due to power outages,
integrity, and availability (CIA) is a model designed to guide hardware failures, and system upgrades. Availability is best
policies for information security within an organization. The ensured by rigorously maintaining all hardware, performing
CIA triad of confidentiality, integrity, and availability is at hardware repairs immediately when needed, providing a
the heart of information security. The members of the certain measure of redundancy and failover, providing
Classic Information Security triad -confidentiality, integrity adequate communications bandwidth and preventing the

196

Copyright Free under CC BY Licence


occurrence of bottle necks, implementing emergency emphasizes the importance of information security. Assets
backup power systems, keeping current with all necessary held on internal Intranets may increase the interest of
system upgrades, and guarding against malicious actions potential misusers. Hence, protecting Intranets and the
such as denial-of-service (DoS) attacks. data and information transmitted via them against various
threats endangering the confidentiality, integrity and
In addition to the above mentioned three members, availability of information is an extremely important
Authenticity and Non-repudiation are also considered to consideration.
be members of the CIA model.
Using the Internet as a part of an Intranet poses a serious
threat, because the Internet is inherently nonsecure. As a
Authenticity
result, users must be very careful particularly in encrypting
Authenticity is the process of ensuring that the data, their communications. Imitation (spoofing), reply (rapid fire),
transactions, communications or documents are genuine. alteration of message contents (superzapping), prevention
It is also important for authenticity to validate that the of service availability and active and passive wiretapping
parties involved are genuine. Some information security are among the most malicious threats. Wiretapping, for
systems incorporate authentication features such as example, could lead to a situation where strategic
"digital signatures", which give evidence that the messaged knowledge regarding an organization gets in the hands of
data is genuine and was sent by someone possessing outsiders, if communication encryption is not implemented
the proper signing key. by means of strong encryption methods.
Hacker tools, although developed for the Internet, are also
Non-repudiation usable on Intranets. They can be software or hardware
based or a combination of both. Their authorized use
Non-repudiation means a person's intention to fulfill his includes finding and correcting information security
obligations to a contract. It also implies that one party of a weaknesses on Intranets. However, they also enable
transaction cannot say that they have not received a insiders to hack such communication systems and access
transaction nor can the other party deny having sent a information which they are not authorized to access.
transaction.
Relation Between information Security and
It is important to note that while technology such as Cybersecurity
cryptographic systems can assist in non-repudiation
efforts, the concept is basically a legal concept. It is not, Information Security, mentioned in the earlier sections is
for instance, sufficient to show that the message matches the protection of information and information systems from
a digital signature signed with the sender's private key, unauthorized access, use, disclosure, disruption,
and thus only the sender could have sent the message modification, or destruction in order to provide
and nobody else could have altered it in transit. The alleged confidentiality, integrity, and availability.
sender could in return demonstrate that the digital signature Cybersecurity on the other hand can be defined as the
algorithm is vulnerable or flawed, or allege or prove that ability to protect or defend the use of cyberspace from
his signing key has been compromised. The fault for these cyber-attacks. Cyberspace is "the environment in which
violations may or may not lie with the sender himself, and communication over computer networks occurs."
such assertions may or may not relieve the sender of
liability, but the assertion would invalidate the claim that Cyber security involves anything security-related in the
the signature necessarily proves authenticity and integrity cyber domain or realm (or cyberspace). Information security
and thus prevents repudiation. involves the security of information or information systems
regardless of the realm it occurs in (e.g., risk of exposure
With all activities that give us almost unlimited freedom, in physical world). Since anything that occurs in the cyber
there are risks. Because the Internet is so easily accessible realm would involve the protection of information and
to anyone, it can be a dangerous place. Know who you're information systems in some way, you can conclude that
dealing with or what you're getting into. Predators, cyber information security is a super-set of cyber security.
criminals, bullies, and corrupt businesses will try to take (Fig 1) At times the two terms are used interchangeably
advantage of the unwary visitor. too.

The internet, Intranet and Security Key Challenges in Information Security

Although the difference between Intranets and the Internet 1 IT Security is assigned a low priority
is not great in terms of technology, the transmission of
information is completely different from the organizational • The organization have not instilled the right focus
point of view. on implementing IT security practices.
2 Ad hoc Security Governance
Information security threats between Intranets and other
networks and information systems are rather similar. The • Absence of an Information Security Management
use of Intranets as internal information channels System (ISMS) or a structured governance
mechanism. (Fig 1)
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.136 197

Copyright Free under CC BY Licence


Fig 1

Relation between Information Security and Cybersecurity

3 Ambiguity in roles and responsibilities Benefits of Information Security:

• Ambiguities exist on the roles and responsibilities • Protect networks, computers and data from
of the different players (Business, teams in SSO, unauthorized access to minimize the impact from
etc.) in an SSO. Single sign-on (SSO) is a property external threats of various cybercrime
of access control of multiple related, but • Improved information security and business continuity
independent software systems. With this property management to implement technical, management,
a user logs in once and gains access to all systems administrative and operational controls, which is the
without being prompted to log in again at each of most cost effective way of reducing risk.
them
• Improved stakeholder confidence in information security
4 Inadequate Separation of Duties arrangements.
• Overlapping and shared responsibilities in an SSO • Improved company credentials with the correct security
makes it difficult to implement appropriate level of controls in place Organization will improve credibility
separation in duties. and trust among internal stakeholder and external
5 Varied Interpretations of Security Requirements vendors. The credibility and trust are the key factors to
win a business.
• In the absence of standard interpretations, the
different individuals and teams have their own • Faster recovery times in the event of disruption
interpretations.
Techniques to enforce IS in an organization
6 Tendency to reduce Risk level
• The teams show a tendency to reduce the 'Risk Identifying tools to enforce Information Security
Level' to bypass the rigors of the governing
processes. A successful information security policy provides several
benefits to corporations. Enforceable policies ensure that
7 Multiple vendors vulnerabilities are identified and addressed. This results in
• Relentless competition and sense of insecurity have protecting business continuity and strengthening the IT
led to reluctance in sharing responsibility and little infrastructure. When employees throughout an organization
or no collaboration among the vendors. follow a security policy, ensuring that information is safely
shared within the organization as well as with customers,
8 Business/Operations spread across multiple partners and vendors, the risk is reduced.
geographics
• The organization is based out of and functions from 1 The first step to creating an effective information
multiple locations spread all across the globe. security policy is evaluating information assets and
identifying threats to those assets.
9 Lack of Training/Awareness
Some assets within an organization will be more
• Inadequate training and awareness on security valuable than others, but monetary value should not be
practices.
198 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.136

Copyright Free under CC BY Licence


the only factor. Determining both the monetary value members are expected to follow. Security policy applies
and the intrinsic value of an asset is essential in to all hardware, software, data, information, network,
accurately gauging its worth. To calculate an asset's personal computing devices, support personnel, and users
monetary value, an organization should consider the within an organization.
impact if that asset's data, networks or systems are
compromised in any way. To calculate intrinsic value, For an IT security system to work, a well-defined framework
an organization must consider a security incident's needs to be developed involving all stakeholders, and it
impact on credibility, reputation and relationships with needs to be updated over time to be useful. The information
key stakeholders. security frameworks facilitate the management process
in considering the handling of data and implementation of
2 Creating a policy is for organizations to perform system/ process in the form of identifying assets,
a risk assessment determining security requirement, risk assessment, control
evaluation, control implementation, process monitoring and
After the identification of assets and threats, the next
update.
step in creating a policy is for organizations to perform
a risk assessment. This assessment allows an The commonly used terms in Information Security
organization to decide whether information is under Framework are:
protected, overprotected or adequately protected. The
goal for this risk assessment should be to minimize • Policy: General Management Statements
expenses without exposing an organization to
• Standards: Specific Mandatory Controls
unnecessary risk. This assessment will help in
determining the proper allocation of resources once • Guidelines: Recommendations / Best Practices
the security policy is effectively in place. • Procedures: Step by Step Instructions
The Information Security Framework The detailed activities involved in actually implementing a
The Information Security Framework establishes security Security Framework, the sequence of practice to be
policy and practices for an organization. Policies provide followed, corrrective actions to be taken are shown in the
guidance on matters affecting security that an organization's Figure shown below. (Fig 2).

Fig 2

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.136 199

Copyright Free under CC BY Licence


The major heads and the practices under each head in a
Framework are as shown below.

Identify Protect Detect Respond Recover

• Asset • Access Control • Anomalies and • Response Planning • Recovery


Management Events Planning
• Business • Awareness and • Security Continuous • Communications • Improvement
Environment Training Monitoring
• Data Security
• Governance • Information Protection • Detection Process • Analysis • Communications
and Procedures
• Risk • Maintenance • Mitigation
Assessment
• Risk • Protective technology • Improvements
Management
Strategy

Thus the security framework becomes the technology that New technologies and new networks can plug into the
turns security policies into practice. It achieves it by the security framework and Security costs become more
four steps cycle of plan, do act and check cycle. The predictable and manageable.
PPT triad, ie. people, process and technology needs to
be given equal importance in achieving this.

200 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.136

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.5.137
COPA - Cyber Security

Overview of security threats


Objectives: At the end of this lesson you shall be able to
• describe security threat and its types
• describe the methods of identifying threats
• explain how threats affect a system
• describe the sources of threats
• describe the best practices to identify and mitigate threats.

Introduction 8 Phishing
A form of social engineering, involving the sending of
A Threat is any circumstance or event with the potential to
legitimate looking emails aimed at fraudulently
cause harm to the system or activity in the form of
extracting sensitive information from recipients, usually
destruction, disclosure, and modification of data, or denial
to gain access to systems or for identity theft.
of service. A threat is a potential for harm. The presence of
a threat does not mean that it will necessarily cause actual 9 System Compromise
harm.
A system that has been attacked and taken over by
malicious individuals or 'hackers', usually through the
Some of the common terms associated with threats and
exploitation of one or more vulnerabilities, and then often
their description are as follows:
used for attacking other systems.
1 Unauthorized Access 9 Spam
The attempted or successful access of information or Unsolicited email sent in bulk to many individuals,
systems, without permission or rights to do so. usually for commercial gain, but increasingly for
spreading malware.
2 Cyber Espionage
10 Denial of Service
The act of spying through the use of computers,
involving the covert access or 'hacking' of company or An intentional or unintentional attack on a system and
government networks to obtain sensitive information. the information stored on it, rendering the system
unavailable and inaccessible to authorized users.
3 Malware
11 Identity Theft
A collective term for malicious software, such as
viruses, worms and trojans; designed to infiltrate The theft of an unknowing individual's personal
systems and information for criminal, commercial or information, in order to fraudulently assume that
destructive purposes. individual's identity to commit a crime, usually for
financial gain.
4 Data Leakage
The intentional or accidental loss, theft or exposure of Categories of threats
sensitive company or personal information.
Security Threats can be classified in many ways. A few of
5 Mobile Device Attack
the popular classifications are as follows:
The malicious attack on, or unauthorized access of,
mobile devices and the information stored or processed 1 Based on the sophistication, Security threats can be
by them; performed wirelessly or through physical classified into three categories.
possession.
• Simple first-generation threats are generic virus-type
6 Social Engineering
attacks spread by users opening infected e-mail
Tricking and manipulating others by phone, email, and inconspicuous file attachments.
online or in-person, into divulging sensitive information,
• The second-generation threats are more
in order to access company information or systems.
sophisticated and pose bigger problems. Created
7 Insiders with automated tools, these worms attack
vulnerabilities without human interaction.
An employee or worker with malicious intent to steal
Replication, identification, and targeting of new
sensitive company information, commit fraud or cause
victims is automatic.
damage to company systems or information.

201

Copyright Free under CC BY Licence


• The third generation threats are blended threats, Threats based on technology
are common and incorporate viruses, Trojans and
automation. These worms pre-compile targets for 1 Threats based on WWW technology
hyper-propagation, exploit known vulnerabilities and 2 New features in browser software
enable targeted use of hidden vulnerabilities. They
also target multiple attack wireless links, virtual 3 Browser software test versions
private networks and attack inside perimeter 4 Server software
defences such as firewalls and intrusion detection
systems. 5 CGI scripts
6 Cookies
2 The top threats according to OWASP (Open Web
Applications Security Project) are as follows: 7 Threats based on Unix and TCP/IP tools
8 Difficulties in firewall management
• Injection
9 Use of cryptographic software
• Cross Site Scripting (CSS)
10 Hacker tools
• Broken Authentication and Session Management
11 Other software based threats
• Insecure Direct Object References
12 Intranet application software
• Cross - Site Request Forgery (CSRF)
13 Java language
• Security Misconfiguration
14 ActiveX
• Insecure Cryptographic Storage
15 Threats based on communications
• Failure to Restrict URL Access
16 Threats based on viruses
• Insufficient Transport Layer Protection
17 Threats based on human activities
• Unvalidated Redirects and Forwards
Identification of Information Security Threats
3 Categorization by Microsoft according to the kinds of
Exploits that are used (or motivation of the attacker) The success of an information security management
ie. STRIDE system. The STRIDE acronym is formed program is based on the accurate identification of the
from the first letter of each of the following categories. threats to the organization's information systems.
• Spoofing identity. An example of identity spoofing Identification of Information Security Threats is an essential
is illegally accessing and then using another user's first step for security planners. Proper threat and
authentication information, such as username and vulnerability identification should include security testing
password. and inspections, which are geared to promoting and
ensuring that equipment is operating properly, is readily
• Tampering with data. Data tampering involves the available when needed, and that employees are proficient
malicious modification of data. in the use of the equipment.
• Repudiation. Repudiation threats are associated
with users who deny performing an action without To accomplish this, systems must design a testing
other parties having any way to prove otherwise-for program that not only assesses the current state of
example, a user performs an illegal operation in a security, but can also be used to upgrade staff effectiveness
system that lacks the ability to trace the prohibited through training.
operations.
The two major methods of identifying security threats are
• Information disclosure. Information disclosure Probing and Scanning.
threats involve the exposure of information to
individuals who are not supposed to have access Probing is an attempt to gain access to a computer and
to it. its files through a known or probable weak point in the
• Denial of service. Denial of service (DoS) attacks computer system. It is an action taken for the purpose of
deny service to valid users. learning something about the state of the network.

• Elevation of privilege. In this type of threat, an Scanning is a method to go through all the files, or network
unprivileged user gains privileged access and elements with an intention to detect something unusual.
thereby has sufficient access to compromise or File scanning inspects files that users attempt to download
destroy the entire system. or open remotely for viruses and other malicious content.
File scanning returns some information for policy
enforcement.

202 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.137

Copyright Free under CC BY Licence


There are 2 types of file scanning. They can be used Infection
together.
Infection is the means used by the threat to get into the
• Advanced detection applies techniques to discover device. It can either use one of the faults previously
known and emerging threats, including viruses, Trojan presented or may use the gullibility of the user. Infections
horses, worms, and others. may ask for permission, or may interact with the gullible
user or may not even do any of these two and directly
• Anti-virus scanning uses anti-virus definition files to
attack the system.
identify virus-infected files.
Network scanning is a procedure for identifying active hosts Accomplishment of the goal
on a network for the purpose of network security
assessment. Scanning procedures, such as ping sweeps Once the threat has infected a device it will also seek to
and port scans, return information about which IP accomplish its goal, which is usually one of the following:
addresses map to live hosts that are active on the Internet hardware damage, denial of service(DoS), monetary
and any suspicious activity etc. damage, damage data and/or , device, and concealed
damage etc.
Modus Operandi of Threats in attacking a system
Spreading to other systems
Typically an attack on a device takes place in 3 phases:
Once the threat has infected a device, it always aims to
• The infection of a host, spread one way or another.
• The accomplishment of its goal, and
It can spread through networks, wired or wireless, through
• The spread of the malware to other systems. the internet, proximate devices using Wi-Fi, Bluetooth and
infrared light and through shared devices etc.
Threats often use the resources offered by the infected
devices. They use the output devices such as Bluetooth Sources of Threats (Fig 1)
or infrared, but may also use the address book or email
address of the person to infect the user's acquaintances. Primary sources of threats are employees/insiders,
They exploit the trust that is given to data sent by an malicious hackers, natural disasters, foreign adversaries,
acquaintance. and hostile attacks. In several cases, the areas for sources

Fig 1

of threats may overlap. For example, hostile attacks may Human Threats
be performed by foreign adversaries or a disgruntled
A Employees/Insiders
employee.
Intentional and accidental errors and malicious acts by
Natural Disasters employees and insiders cause a considerable amount of
damages and losses experienced in the
Earthquakes, hurricanes, floods, lightning, and fire can telecommunications industry.
cause severe damage to computer systems. Information
can be lost, down time or loss of productivity can occur, Disgruntled employees can create both mischief and
and damage to hardware can disrupt other essential sabotage on a computer system. Staff removed from their
services. Few safeguards can be implemented against jobs in both public and private sectors has created a group
natural disasters. The best approach is to have disaster of individuals with important organizational knowledge who
recovery plans and contingency plans in place. may retain potential system access. System managers
can limit this threat by invalidating passwords and deleting
system accounts in a timely manner.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.137 203

Copyright Free under CC BY Licence


Malicious Hackers Hostile Attacks

Malicious threats consist of inside attacks by disgruntled Through hostile attacks, it is possible to affect the
or malicious employees and outside attacks by non- availability of the networks. The primary impact of hostile
employees just looking to harm and disrupt an attacks such as coordinated nuclear attacks, limited/
organization. Malicious attackers normally will have a uncoordinated nuclear attacks, nuclear accidents,
specific goal, objective, or motive for an attack on a system. terrorism, electronic warfare, sabotage, and civil disorder
These goals could be to disrupt services and the continuity on the a nation's network is disruption and denial of service.
of business operations by using denial-of-service (DoS) Such disasters impact the timeliness and quality of the
attack tools. They might also want to steal information or delivered services.
even steal hardware such as laptop computers. Hackers
can sell information that can be useful to competitors. B Non-Malicious Employees
Attackers are not the only ones who can harm an
The most dangerous attackers are usually insiders (or
organization. The primary threat to data integrity comes
former insiders), because they know many of the codes
from ignorant users. These are authorized users who are
and security measures that are already in place. Insiders
not aware of the actions they are performing. Errors and
are likely to have specific goals and objectives, and have
omissions can lose, damage, or alter valuable data.
legitimate access to the system. Employees are the
people most familiar with the organization's computers
Users, data entry clerks, system operators, and
and applications, and they are most likely to know what
programmers frequently make unintentional errors that
actions might cause the most damage. Insiders can plant
contribute to security problems, directly and indirectly.
viruses, Trojan horses, or worms, and they can browse
Sometimes the error is the threat, such as a data entry
through the file system.
error or a programming error that crashes a system. In
other cases, errors create vulnerabilities.
However, disgruntled current employees actually cause
more damage than former employees. Common examples
Best Practices or Guidelines used to Identify Threats
of computer-related employee sabotage include:
Different mechanisms and methodologies can be used to
• Changing data
successfully identify threats/attacks depending on their
• Deleting data type. In other words, depending on the threat, you can
use specific techniques to identify and classify them
• Destroying data or programs with logic bombs
accordingly. Following are the most common
• Crashing systems methodologies:
• Holding data hostage
• The use of anomaly detection tools
• Destroying hardware facilities
• Network telemetry using flow-based analysis
• Entering data incorrectly
• The use of intrusion detection and intrusion prevention
Foreign Adversaries systems (IDS/IPS)
• Analyzing network component logs (that is, SYSLOG
Computer intruder activities have occurred internationally,
from different network devices, accounting records,
with the number of attempted intrusions through
application logs, Simple Network Management Protocol
international gateways is increasing at an alarming rate.
(SNMP) etc.
There have been few indications that computer
undergrounds within foreign countries carry over political Best Practices or Guidelines used in mitigation of
agendas. Sometimes intelligence services of one country threats
directly target, penetrate, or compromise the
Communications systems of other countries. The following are some of the practices which when
implemented are likely to reduce the threats to the security
Outside Attackers or 'Crackers' of an organization's information, data and credibility.

People often refer to "crackers" as "hackers." The term Security Awareness Training
hacker refers to people who either break in to systems for
• Most security breaches actually originate inside
which they have no authorization or intentionally overstep
companies by disgruntled or negligent employees. So
their bounds on systems for which they do not have
educate everyone in your company so they can help
legitimate access. Common methods for gaining access
identify a variety of security risks.
to a system include password cracking, exploiting known
security weaknesses, network spoofing, and social • Employees should be able to spot and identify email
engineering. phishing and spoofing attacks. They should also be
trained not to store, send or copy sensitive information
that's unencrypted.

204 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.137

Copyright Free under CC BY Licence


• They should know not to share sensitive information Access Controls
over the phone unless they are 100% sure of the • For increased security, give employees only (and
audience. partners) access to the data they need. This includes
• Train employees on security policies and practices. both physical and logical access.
And make sure to update them and retrain at frequently. • Start by granting the least privilege. You can then
• Training materials should also review corporate policies escalate privileges to allow access to unauthorized data
and clearly detail consequences for any suspicious or on an as-needed basis.
malicious behavior amongst employees. They should Mobile Devices
be trained on various security policies, including:
• Laptops, smartphones, and tablets have increased the
- Acceptable Use and Unacceptable Use productivity and mobility of today's workforce. But along
- General Use and Ownership with that productivity comes vulnerability. Lost or stolen
laptops and other mobile devices are the top cause of
- Security & Proprietary Information data breaches.
- Blogging & Social Media • Enable auto-lock or require a password to access all
- Enforcement ie. the disciplinary action for non- devices.
compliance Monitoring
- Social Media • Make sure your business is set up to monitor systems
- Bring Your Own Device Policies and network devices for any abnormalities.
- Data Policy • Collect and correlate information from all places or
infrastructure - network, systems, and user activity.
- Mobile Device Management (MDM) Policy
• Don't just block activity at a firewall or IPS. Log it, review
- Mobile Device Support Policy it and learn from it.
- Policies Regarding Company-issued Devices • Install content filtering to monitor user activity from
- Loss & Theft within your business. The most common form of
employee misuse of the Internet is to surf unwanted
- Employee Termination Policy sites
- Security Incident Management Firewall
Anti-Virus & Anti-Malware Protection • Configure Firewall rules and Policies because a firewall
• Common forms of malware include: Worms, Key is the first line of defense against any attack (network
loggers, Video frame grabbers, Rootkits and Trojan or host). It acts a barrier between a public network and
horses. a private network.
• Install, update, schedule and run good Antivirus Remote Backup
programs. • Backup your data regularly to a remote location. Backup
• Adopt an "end point security" strategy to combat is one of the most neglected areas of computing and
malware threats. Endpoint security is an information therefore typically one of the biggest opportunities your
security concept that means that each device (or business has to mitigate risk.
endpoint) on a network should be responsible for and • Often, businesses invest in securing data from hackers
capable of providing for its own security. or malware, but then the data is physically destroyed
• Whatever your anti-malware solution, it should scan by natural causes. If the data doesn't exist, securing it
email for attached viruses, monitor files in real time for from outside threats has no meaning.
infections, and perform thorough scans of every file. Security Assessments & Penetration Testing
Data Encryption • To secure your business you must stay vigilant. There
• Data encryption is a powerful part of information are always people with wrong intentions looking for the
security. Encryption protects your data even after it next way to compromise your business's information
has been accessed. • Perform annual or, better, quarterly vulnerability
Patching assessments to identify new risks. The ever-changing
security environment is always creating new risks.
• Patching is essential to minimizing the risk to your
computer systems. Patches are often released to fix • Identify the new risks that apply to your business and
security holes in systems and applications. Make sure fix them before someone else finds them.
you keep all operating systems and applications you •
Get a formal Information Security Risk Assessment
run patched. Install the latest firmware updates on all done every three years, which is the life cycle of most
network devices. products these days.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.137 205

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.5.138
COPA - Cyber Security

Information security vulnerabilities and Risk Management


Objectives: At the end of this lesson you shall be able to
• describe security vulnerability
• describe the types of vulnerabilities
• explain how threats affect a system
• describe the vulnerability assessment tools and techniques
• describe the best practices to mitigate security vulnerabilities
• describe the relation between threat, vulnerability and risk
• describe the various threat agents
• describe the purpose of risk management
• describe the types of risk management
• explain the risks to ICT supply chain management.

Introduction undesirable event compromising the security of the


computer system, network, application, or protocol involved.
In computer security, a vulnerability is a software,
hardware, procedural, or human weakness which allows A Types of Technical Vulnerabilities
an attacker to reduce a system's information assurance.
A vulnerability is a weakness that may provide an attacker Most software security vulnerabilities fall into one of a small
the open door he is looking for to enter a computer or set of categories:
network and have unauthorized access to resources within
the environment. It represents the absence or weakness • buffer overflows
of a safety measure that could be exploited. • unvalidated input

Threat, Threat Agent, Exploit, Risk and Vulnerability. • race conditions


• access-control problems
• A threat is any potential danger to information or
systems. The threat is that someone, or something, • weaknesses in authentication, authorization, or
will identify a specific vulnerability and use it against cryptographic practices
the company or individual.
Buffer Overflows
• The entity that takes advantage of a vulnerability is
referred to as a threat agent. A buffer overflow, considered to be a major source of
• An exploit is a means of taking advantage of the vulnerabilities, occurs when an application attempts to write
vulnerability and using it to take advantage of a system data beyond the end (or, occasionally, before the beginning)
or network. of a buffer. Buffer overflows can cause applications to crash,
can compromise data, and can provide an attack vector
• A risk is the likelihood of a threat agent taking advantage for further privilege escalation to compromise the system
of a vulnerability and the corresponding business on which the application is running. Buffer overflow attacks
impact. generally occur by compromising either the stack, the
heap, or both.
In other words, a threat is what we're trying to protect
against, a vulnerability is a weakness or gap in our Unvalidated Input
protection efforts.
As a general rule, you should check all input received by
Why do Information Security Vulnerabilities exist? your program to make sure that the data is reasonable or
valid. In cases where invalid data is allowed or accepted,
Vulnerabilities exist because of exploits in code or a normal program attempting to read such a file would
networking protocols. Millions of lines of code are required attempt to allocate a buffer of an incorrect size, leading to
to make an operating system, and sometimes the potential for a heap overflow attack or other problem.
vulnerabilities can be found within. If a firewall has several For this reason, you must check your input data carefully.
ports open, there is a higher likelihood that an intruder will This process is commonly known as input validation or
use one to access the network in an unauthorized method. sanity checking.
Vulnerability could be the result of "a flaw or weakness in
hardware, software or process that exposes a system to Any input received by your program from an untrusted
compromise". It is the existence of a weakness, design, source is a potential target for attack. Hackers look at
or implementation error that can lead to an unexpected, every source of input to the program and attempt to pass

206

Copyright Free under CC BY Licence


in malformed data of every type they can imagine. If the • Vulnerabilities in the Java class library on which an
program crashes or otherwise misbehaves, the hacker then application depends for its security
tries to find a way to exploit the problem.
Understanding Security Vulnerabilities
Race Conditions
Flaws in Software or Protocol Designs
A race condition occurs when a pair of routine programming
calls in an application do not perform in the sequential Fundamental mistakes and oversight in Software design
manner that was intended to as per rules. It is a timing are the causes of design vulnerabilities. Design flaws result
event within software that can become a security in software not being secure thus making it a high level
vulnerability if the calls are not performed in the correct vulnerability case.
order. If the correct order of execution is required for the
proper functioning of the program, this is a bug. If an Computer networks depend on protocols that specify the
attacker can take advantage of the situation to insert messages that are exchanged at runtime, their format and
malicious code, change a filename, or otherwise interfere structure. Protocols are linked with different protocol
with the normal operation of the program, the race condition stacks, e.g., TCP/IP, or different models, e.g., OSI, and
is a security vulnerability. Attackers can sometimes take many protocols with underspecified security are still
advantage of small time gaps in the processing of code to present in practice. Some of the vulnerabilities arising due
interfere with the sequence of operations, which they then to flawed protocols are described below:
exploit.
A. TCP/IP. The TCP/IP protocol stack has some weak
In software development, time of check to time of use points that allow:
(TOCTTOU or TOCTOU, pronounced "TOCK too") is a
class of software bug caused by changes in a system • Spoofing : A spoofing attack is when a malicious party
between the checking of a condition (such as a security impersonates another device or user on a network in
credential) and the use of the results. This is one example order to launch attacks against network hosts, steal
of a race condition. data, spread malware, or bypass access controls. There
are several different types of spoofing attacks that
Interprocess Communication(IPC) malicious parties can use to accomplish this. They
are IP Address Spoofing Attacks, ARP (Address
Interprocess communication (IPC) is a set of programming Resolution Protocol ) Spoofing Attacks, DNS Server
interfaces that allow a programmer to coordinate activities Spoofing Attacks, etc.
among different program processes that can run • Telnet protocol : Telnet can be used to administer
concurrently in an operating system. This allows a program systems running Microsoft Windows 2000 and Unix.
to handle many user requests at the same time. These When using the telnet client to connect from a Microsoft
messaging protocols used for interprocess communication system to UNIX system and vice versa, user names
are often vulnerable to attack. and passwords are transmitted in clear text thus
creating security vulnerability.
Remote Procedure Call (RPC) is an interprocess
communication mechanism that allows a program running • File Transfer Protocol (FTP) : File Transfer Protocol
on one host to run code on a remote host. allows users to connect to remote systems and transfer
files back and forth. As part of establishing a connection
Insecure File Operations to a remote computer, FTP relies on a user name and
password combination for authentication. Use of FTP
In addition to time-of-check-time-of-use problems, many
poses a security problem similar to use of the Telnet
other file operations are insecure. Programmers often make
protocol because passwords typed to FTP are
assumptions about the ownership, location, or attributes
transmitted over the network in plain text, one character
of a file that might not be true. For example, you might
per packet. These packets can be intercepted.
assume that you can always write to a file created by
your program. However, if an attacker can change the • Weaknesses in how protocols and software are
permissions or flags on that file after you create it, and if implemented
you fail to check the result code after a write operation,
Even when a protocol is well designed, it can be vulnerable
you will not detect the fact that the file has been tampered
because of the way it is implemented. For example, a
with.
protocol for electronic mail may be implemented in a way
that permits intruders to connect to the mail port of the
B Types of Native Vulnerabilities
victim's machine and fool the machine into performing a
task not intended by the service. This type of vulnerability
Examples of Native Vulnerabilities are:
enables intruders to attack the victim's machine from
• Vulnerabilities in the sandboxing mechanism which remote sites without access to an account on the victim's
allow untrusted bytecode to circumvent the restrictions system.
imposed by the security manager

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138 207

Copyright Free under CC BY Licence


• Software may be vulnerable because of flaws that were D Insecure Cryptography
not identified before the software was released. This
type of vulnerability has a wide range of subclasses, Attackers' can decode any cryptographic mechanism or
which intruders often exploit using their own attack tools algorithm as main methods to hack them are discovered.
like race conditions in file access, non-existent checking
of data content and size etc. E Data Protection and Portability

Weaknesses in System and Network Configurations Although the cloud services are offered based on a contract
among client and a provider but what will happen when the
• System administrators and users may neglect to contract is terminated and client doesn't wants to continue
change the default settings in network configurations, anymore.
or they may simply set up their system to operate in a
way that leaves the network vulnerable. F Vendor Lock-in
• Asynchronous transfer mode (ATM). Security can be This vulnerability occurs due to immature providers and
compromised by what is referred to as "manhole new business models which raise the risk of failure and
manipulation"-direct access to network cables and going out of the business.
connections in underground parking garages and
elevator shafts. G Internet Dependency
• Frame relay. Similar to the ATM problem.
Cloud computing is an internet dependent technology
• Device administration. Switches and routers are easily where users are accessing the services via web browser.
managed by an HTTP interface or through a command What if the internet is not available or service is down,
line interface. Coupled to the use of weak passwords what will happen to users systems and operations that
(for example, public passwords), it allows anybody with are very critical and need to run 24 hours such as
some technical knowledge to take control of the device. Healthcare and Banking systems.
• Modems. A modem bypasses the "firewall" that protects
a network from outside intruders. A hacker using a "war Weaknesses in Online e-transactions
dialer" tool to identify the modem telephone number
and a "password cracker" tool to break a weak The tremendous increase in online transactions has been
password can gain access to the system. accompanied by an equal rise in the number and type of
attacks against the security of online payment systems.
• Weaknesses in Web or Cloud applications Some of these attacks have utilized vulnerabilities that
There are several significant vulnerabilities that should be have been published in reusable third-party components
considered when an organization is ready to move their utilized by websites, such as shopping cart software. Other
critical applications and data to a cloud computing attacks have used vulnerabilities that are common in any
environment, these vulnerabilities are described below : web application, such as SQL injection or cross-site
scripting.
A Session Riding and Hijacking
The common types of vulnerabilities in Online e-
Session riding refers to the hackers sending commands transactions are SQL injection, cross-site scripting,
to a web application on behalf of the targeted user by just information disclosure, path disclosure, price manipulation,
sending that user an email or tricking the user into visiting and buffer overflows.
a specially crafted website. Session riding deletes user Successful exploitation of these vulnerabilities can lead
data, executes online transactions like bids or orders, to a wide range of results. Information and path disclosure
sends spam to an intranet system via internet and changes vulnerabilities will typically act as initial stages leading to
system as well as network configurations or even opens further exploitation. SQL injection or price manipulation
the firewall. attacks could cripple the website, compromise
confidentiality, and in worst cases cause the e-commerce
B Virtual Machine Escape business to shut down completely.
VM escape is a vulnerability that enables a guest-level One of the main reasons for such vulnerabilities is the fact
VM to attack its host. Under this vulnerability an attacker that web application developers are often not very well
runs code on a VM that allows an OS running within it to versed with secure programming techniques.
break out and interact directly with the hypervisor.
Browser Security and Role of cookies and pop-ups
C Reliability and Availability of Service
Security vulnerabilities may allow a cookie's data to be
The cloud storage infrastructure may go down for a read by a hacker, used to gain access to user data, or
considerable time, causing data loss and access issues used to gain access (with the user's credentials) to the
with web services. website to which the cookie belongs.

208 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138

Copyright Free under CC BY Licence


Pop-up ads or pop-ups Some of the vulnerabilities in Smartphones are Data
leakage resulting from device loss or theft, Unintentional
The "security" risks from popup windows are phishing, disclosure of data, Attacks on decommissioned
trapping to unwanted web sites etc. smartphones, Phishing attacks, Spyware attacks, Network
Spoofing Attacks, Surveillance(user under surveillance)
Security holes in Browser, Web Applications, OS, and attacks, Diallerware attacks(Stealing money), Financial
Smartphones malware attacks(Stealing credentials) and Network
congestion.
In security terminology, a hole refers to a software or
operating system vulnerability that could be exploited to Vulnerability Assessment Tools and Techniques
compromise the overall security of the computer system
or network on which the hole resides.The three different Vulnerability Assessment is a Security Exercise that
kinds of vulnerabilities are: identifies weaknesses, identifies and enumerates
vulnerabilities and reports on the discoveries about security
• Operating system vulnerabilities are those affecting the liabilities within networks, applications and systems.
Linux kernel; or components that ship with an operating
system produced by Microsoft, Apple, or a proprietary The Vulnerability Assessment detects vulnerabilities
Unix vendor, and defined as part of the operating via:
system by the vendor.
• Security technologies
• Browser vulnerabilities are those affecting components
defined as part of a web browser. This includes web - VA Scanners, Appliances and Software
browsers that ship with operating systems, such as
• Remediation technologies
Windows Internet Explorer and Apple's Safari, along
with third-party browsers, such as Mozilla Firefox and - Patch Management Systems(WSUS, SCCM,
Google Chrome. LanDesk,VMWare Update manager)
• Application vulnerabilities are those affecting all other
Vulnerability Assessment involves mainly the
components, including components published by
following three steps:
operating system vendors and other vendors.
Vulnerabilities in open source components that may • Information Gathering and Discovery which includes
ship with Linux distributions (such as the X Window Network Scanning, Ports Scanning, Directory Services
System, the GNOME desktop environment, GIMP, and and DNS Zones and Registers.
others) are considered application vulnerabilities. • Enumeration which includes Hosts and OS, Ports,
Services and their versions, information and SNMP
Security holes in Web Applications communities
The following is a list of top 10 threats in the OWASP(Open • Detection involving Identification of Weaknesses,
Web Applications Security project) category. Identification of Vulnerabilities, Report Generation and
Use of remediation tools.
Injection (Sqli -> SQL Injection),Broken Authentication &
Session Management, XSS (Cross Site Scripting),Insecure Vulnerability Assessment tools:
Direct Object Reference, Security Misconfiguration,
Sensitive Data Exposure, Missing Function Level Access Vulnerability Assessment tools detect, identify, measure
Control, Cross Site Request Forgery (CSRF Or XSRF), the effect of the vulnerabilities found at various levels. Most
Using Components With Known Vulnerabilities and Vulnerability Assessment tools are capable of scanning a
Unvalidated Redirect & Forwards. number of network nodes, including networking and
networked devices (switches, firewalls, printers, etc.) as
Security holes in OS well as server, desktop and portable computers.

Some of the vulnerabilities in UNIX OS are Setuid problems, Common Vulnerability Assessment Tools are Network
Trojan Horses and Terminal Troubles Scanners, Host Scanners, Database Scanners, Web
Application Scanners, Multilevel Scanners, Automated
Some of the vulnerabilities in Windows OS are Passwords, Penetration test tools and Vulnerability Scan
Peer to Peer File sharing, Vulnerabilities in embedded Consolidators.
automation features in Microsoft Outlook and Outlook
Express that can allow execution of rogue code. Techniques to Exploit Vulnerabilities

Some of the vulnerabilities in LINUX OS are missing Vulnerabilities can be exploited for ex. by the use of packet
permission checks, Uninitialized data, and Memory sniffers. Other tools are used to construct packets with
mismanagement forged addresses; one use of these tools is to mount a
denial-of-service attack in a way that hides the source of
the attack. Intruders also "spoof" computer addresses,
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138 209

Copyright Free under CC BY Licence


masking their real identity and successfully making 15 Make use of the session tracking mechanism built into
connections that would not otherwise be permitted. In this your development framework.
way, they exploit trust relationships between computers.
Risk is the combination of the probability of an event and
The most common exploits occur by the use of Trojans, its consequences. It refers to the likelihood of being
Viruses, Worms, Logic Bombs, Phishing, Forwarding and targeted by a given attack.
sharing Urban legends, Responding to Nigerian Scams
etc. Relationship between Threat, Vulnerability, and Risk

Techniques to Fix the Vulnerabilities Before defining the relationship between threat, vulnerability
and risk let us review the following terms:
Effective remediation demands continuous processes that
together are called Vulnerability Management. The Asset: In information Security, an asset is what we are
processes and related technology defined by vulnerability trying to protect. It may be people, property or information.
management help organizations efficiently find and fix
network security vulnerabilities. Systematic use of these Threat: Anything that can exploit a vulnerability,
processes protects business systems from ever more intentionally or accidentally and obtain, damage or destroy
frequent viruses, worms and other network-borne attacks. an asset.

Continuous Processes of Vulnerability Management Vulnerability: It refers to the weakness or gaps in our
involves Creating security policies & controls, Tracking protection efforts.
inventory / categorizing assets, Scanning systems for
vulnerabilities, Comparing vulnerabilities against inventory, Risk: When a threat exploits a vulnerability, it may cause
Classifying risks, Pre-testing of patches, Applying patches loss, damage or destruction of an asset. This is called a
and Re-scanning and confirming fixes. You can automate Risk.
most of them now with security applications and Web-
based services. Risk is therefore the intersection of assets, threats and
vulnerabilities.
Best Practices and Guidelines to mitigate security
Vulnerabilities ie. assets x threats x vulnerabilities = risk

1 Initialize all variables before use Value of an asset


2 Validate all user input before use
The value placed on information is relative to the parties
3 Restrict administrative permissions on servers and involved, what work was required to develop it, how much
databases it costs to maintain, what damage would result if it were
lost or destroyed, what enemies would pay for it, and what
4 Handle errors and don't display system error messages
liability penalties could be endured. If a company does
to end users
not know the value of the information and the other assets
5 Provide accounts with the least amount of permissions it is trying to protect, it does not know how much money
and privileges required and time it should spend on protecting them. While
assigning values to assets, one needs to consider certain
6 Don't store secrets (e.g. passwords, keys) in your code
issues which are stated as below.
7 Use tested, reliable libraries or modules for common
functions (e.g. authentication, encryption, session • Cost to acquire or develop the asset
tracking)
• Cost to maintain and protect the asset
8 Secure login pages and pages protected by
• Value of the asset to owners and users
authentication with HTTPS
• Value of the asset to adversaries
9 Ensure that server components (OS, software/apps)
are up-to-date • Value of intellectual property that went into developing
the information
10 Avoid installing unnecessary applications on production
servers • Price that others are willing to pay for the asset
11 Remove unused and backup pages from the web server • Cost to replace the asset if lost or damaged
12 If possible, make code libraries and configuration files • Operational and production activities that are affected
inaccessible from the web if the asset is unavailable
13 Disable directory browsing • Liability issues if the asset is compromised
14 Avoid making operating system calls based on user • Usefulness and role of the asset in the organization
input

210 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138

Copyright Free under CC BY Licence


Understanding the value of an asset is the first step to 2 Technical or Logical : These are the virtual,
understanding what security mechanisms should be utilized application and technical controls (systems and
and what funds should go toward protecting it. software), such as firewalls, anti virus software,
encryption and maker/checker application routines.
What Is a Threat Source/Agent? Technical controls are carried out or managed by
computer systems.
A Threat Source or threat Agent is an entity with an
3 Activity phase controls can be either technical or
intention and capability to cause impact.
administrative and are classified as follows based on
Threat agents can take one or more of the following actions the level of risk mitigation:
against an asset: • Preventative controls exist to prevent the threat from
coming in contact with the weakness. These are
• Access - simple unauthorized access controls that prevent the loss or harm from occurring.
• Misuse - unauthorized use of assets (e.g., identity theft, For example, a control that enforces segregation of
setting up a porn distribution service on a compromised responsibilities (one person can submit a payment
server, etc.) request, but a second person must authorize it),
minimizes the chance an employee can issue
• Disclose - the threat agent illicitly discloses sensitive fraudulent payments.
information
• Detective controls exist to identify that the threat
• Modify - unauthorized changes to an asset has landed in our systems. These controls monitor
• Deny access - includes destruction, theft of a non- activity to identify instances where practices or
data asset, etc. procedures were not followed. For example, a
business might reconcile the general ledger or review
The threat agents can be any of the following: payment request audit logs to identify fraudulent
payments.
These individuals and groups can be classified as follows: • Corrective controls exist to mitigate or lessen the
effects of the threat being manifested. Corrective
• Non-Target Specific: Non-Target Specific Threat Agents controls restore the system or process back to the
are computer viruses, worms, trojans and logic bombs. state prior to a harmful event. For example, a
• Employees: Staff, contractors, operational/ business may implement a full restoration of a
maintenance personnel, or security guards who are system from backup tapes after evidence is found
annoyed with the company. that someone has improperly altered the payment
data.
• Organized Crime and Criminals: Criminals target
information that is of value to them, such as bank • Compensating controls are alternate controls
accounts, credit cards or intellectual property that can designed to accomplish the intent of the original
be converted into money. Criminals will often make use controls as closely as possible, when the originally
of insiders to help them. designed controls cannot be used due to limitations
of the environment.
• Corporations: Corporations are engaged in offensive
information warfare or competitive intelligence. Partners Risk likelihood
and competitors come under this category.
• Human, Unintentional: Accidents, carelessness. Risk likelihood is a rough measure of how likely this
particular vulnerability is to be uncovered and exploited by
• Human, Intentional: Insider, outsider. an attacker. It is not necessary to be over-precise in this
• Natural: Flood, fire, lightning, meteor, earthquakes. estimate. Generally, identifying whether the likelihood is
low, medium, or high is sufficient.
Risk Controls
There are a number of factors that can help determine the
If the mitigation of risk is the central focus of Information likelihood. The first set of factors are related to the threat
Security, Controls are the primary tools to achieve this agent involved. The goal is to estimate the likelihood of a
goal. A control is any device or process that is used to successful attack from a group of possible attackers. Note
reduce risk. that there may be multiple threat agents that can exploit a
particular vulnerability, so it's usually best to use the worst-
Basically the three types of controls are : case scenario. For example, an insider may be a much
more likely attacker than an anonymous outsider, but it
1 Administrative : Administrative controls are the actions depends on a number of factors.
that people take. Administrative controls are the
process of developing and ensuring compliance with The first set of factors are related to the threat agent involved.
policy and procedures The goal here is to estimate the likelihood of a successful

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138 211

Copyright Free under CC BY Licence


attack by this group of threat agents. The second factor to vulnerabilities emerge every day. Second, the choice of
be taken into account is the Motive behind the attacks. countermeasures (controls) used to manage risks must
The Access or resources required and the size of the group strike a balance between productivity, cost, effectiveness
of threat agents are the other factors to be considered. of the countermeasure, and the value of the informational
asset being protected.
The next set of factors are related to the vulnerability
involved. The goal here is to estimate the likelihood of the On the contrary, Risk Assessment is executed at discrete
particular vulnerability involved being discovered and time points (ex. once a year, on demand, etc.) and until
exploited. This takes into account the ease of discovery, the performance of the next assessment - provides a
the ease of exploit, the awareness to this group of threat temporary view of assessed risks.
agents, the likelihood of detection of this exploit.
Purpose of Risk Management
Factors for Estimating Impact
The principle reason for managing risk in an organization
When considering the impact of a successful attack, it's is to protect the mission and assets of the organization.
important to realize that there are two kinds of impacts. Therefore, risk management must be a management
The first is the "technical impact" on the application, the function rather than a technical function. Understanding
data it uses, and the functions it provides. The other is the risk, and in particular, understanding the specific risks to
"business impact" on the business and company operating a system allow the system owner to protect the information
the application. system commensurate with its value to the organization.
The fact is that all organizations have limited resources
Ultimately, the business impact is more important. and risk can never be reduced to zero. So, understanding
However, you may not have access to all the information risk, especially the magnitude of the risk, allows
required to figure out the business consequences of a organizations to prioritize scarce resources.
successful exploit. In this case, providing as much detail
about the technical risk will enable the appropriate Risk Assessment (Phases)
business representative to make a decision about the
business risk. The purpose of assessing risk is to assist management in
determining where to direct resources. There are four basic
Technical impact can be broken down into factors aligned strategies for managing risk: mitigation, transference,
with the traditional security areas of concern: confidentiality, acceptance and avoidance.
integrity, availability, and accountability. The goal is to
estimate the magnitude of the impact on the system if the Mitigation
vulnerability were to be exploited. The issues to be Mitigation is the most commonly considered risk
considered are Loss of confidentiality, Loss of integrity, management strategy. Mitigation involves fixing the flaw
Loss of availability and Loss of accountability. or providing some type of compensatory control to reduce
the likelihood or impact associated with the flaw. A common
The factors to be considered for assessing the business
mitigation for a technical security flaw is to install a patch
impact are financial damage, Reputation damage, Non-
provided by the vendor. Sometimes the process of
compliance to policies and Privacy violation.
determining mitigation strategies is called control analysis.
Risk Control Effectiveness
Transference
The risk control effectiveness depends on the Number of
Transference is the process of allowing another party to
systemic risks identified, Percentage of process areas
accept the risk on your behalf. This is not widely done for
involved in risk assessments, Percentage of key risks
IT systems, but everyone does it all the time in their
mitigated and Percentage of key risks monitored among
personal lives. Car, health and life insurance are all ways
many factors involved.
to transfer risk. In these cases, risk is transferred from the
individual to a pool of insurance holders, including the
Risk Management
insurance company. Note that this does not decrease the
likelihood or fix any flaws, but it does reduce the overall
Risk Management and Risk Assessment are major
impact (primarily financial) on the organization.
components of Information Security Management (ISM).
Acceptance
Risk management is the process of identifying
vulnerabilities and threats to the information resources used
Acceptance is the practice of simply allowing the system
by an organization and deciding what countermeasures
to operate with a known risk. Many low risks are simply
to take in reducing the based on the value of the asset.
accepted. Risks that have an extremely high cost to
mitigate are also often accepted. Beware of high risks
The process of risk management is an ongoing, iterative
being accepted by management. Ensure that this strategy
process. It must be repeated indefinitely. The business
environment is constantly changing and new threats and
212 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138

Copyright Free under CC BY Licence


is in writing and accepted by the manager(s) making the tables and the description of the impact, it is possible to
decision. Often risks are accepted that should not have adequately communicate the assessment to the
been accepted, and then when the penetration occurs, organization's management.
the IT security personnel are held responsible. Typically,
business managers, not IT security personnel, are the The risk assessment includes the following actions and
ones authorized to accept risk on behalf of an organization. activities:

Avoidance • Identification of assets;


• Identification of legal and business requirements that
Avoidance is the practice of removing the vulnerable aspect
are relevant for the Identified assets
of the system or even the system itself. For instance,
during a risk assessment, a website was uncovered that • Valuation of the identified assets, taking account of
let vendors view their invoices, using a vendor ID embedded the identified legal and
in the HTML file name as the identification and no • Business requirements and the impacts of a loss of
authentication or authorization per vendor. When notified confidentiality, integrity and availability
about the web pages and the risk to the organization,
management decided to remove the web pages and provide • Identification of significant threats to, and vulnerabilities
vendor invoices via another mechanism. In this case, the of, the identified assets;
risk was avoided by removing the vulnerable web pages. • Assessment of the likelihood of the threats and
vulnerabilities to occur;
Types of Risk Assessment
• Calculation of risk;
Quantitative Risk Assessment • Evaluation of the risks against a predefined risk scale.
Quantitative risk assessment draws upon methodologies Risks to the ICT supply chain management
used by financial institutions and insurance companies.
By assigning values to information, systems, business Risks to the ICT supply chain arise from the loss of
processes, recovery costs, etc., impact, and therefore risk, confidentiality, integrity, or availability of information or
can be measured in terms of direct and indirect costs. information systems and reflect the potential adverse
impacts to organizational operations (including mission,
But it is not commonly used to measure risk in information functions, image, or reputation), organizational assets,
systems because individuals, and other organizations. Such risks can take
the form of sloppy software development, inadequate testing
1 The difficulties in identifying and assigning a value to
of products before they are shipped, and using the least
assets, and
expensive parts even if that means they may not be
2 The lack of statistical information that would make it authentic.
possible to determine frequency.
Supply chain risk management (SCRM) is the process of
Thus, most of the risk assessment tools that are used understanding these risks, their business impacts, and
today for information systems are measurements of how to manage them by mitigating supply chain
qualitative risk. weaknesses and exploits throughout the system lifecycle.

Qualitative Risk Assessment Effective ICT SCRM requires processes, procedures, and
tools that allow organizations to apply SCRM principles
Qualitative risk assessments assume that there is already consistently across all ICT systems. One such principle
a great degree of uncertainty in the likelihood and impact is to minimize the risk of counterfeit parts since they may
values and defines them, and thus risk, in somewhat lead to unpredictable behavior, early failures, or worse. It
subjective or qualitative terms. Similar to the issues in therefore becomes necessary to distinguish counterfeit
quantitative risk assessment, the great difficulty in parts from authentic parts.
qualitative risk assessment is defining the likelihood and
impact values. A structured language to express these characteristics is
needed, such that all members of a supply chain can
Moreover, these values need to be defined in a manner communicate about them, and which can be used to alert
that allows the same scales to be consistently used across others about counterfeits or express the criteria for
multiple risk assessments. Qualitative risk assessments legitimate items. A structured language to describe these
typically give risk results of "High", "Moderate" and "Low". observable attributes of both legitimate and illegitimate
However, by providing the impact and likelihood definition components is one tool for reducing supply chain risk.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138 213

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.5.139
COPA - Cyber Security

Directory services
Objectives: At the end of this lesson you shall be able to
• describe directory and directory service
• describe the benefits of directory services
• mention the various implementations of directory services
• describe the logical and physical structure of active directory
• describe global catalog and group policy.

Introduction 3 Security : Having only one domain means better


security through a single security policy and a single
Directories and directory services set of administrators. If you have multiple domains and
forests, each has its own administrator. One weak but
A directory is a collection or list of data. Real world trusted domain exposes all the other forests and
examples are telephone books, land registers and listings domains. With only a single domain, it's also far easier
of works. All these examples have the purpose of preserving to enforce an organization-wide security policy
information and making it available on demand to the
4 Single platform: A single directory service or Global
concerned persons.
Catalog (GC) means a single platform for all other
Within information technology the term directory is used directory-ware services, including monitoring and
for a special kind of data storage. It allows the structured messaging.
storage and efficient retrieval of objects which are often 5 Faster deployment: starts in an organization with
derived from the real world (e.g. persons, IT equipment). just a single domain and shared account database
The main characteristic of this storage is that all data is solutions need only be deployed once, which means
stored in so called entries. The set of entries within a company-wide deployments are much faster than if the
directory forms a tree (hierarchical database). organization has multiple and separate domains.

Directory Services 6 Single management: infrastructure-Having a single


management infrastructure means there is just one
A directory service is a shared information infrastructure infrastructure for all other directory services tasks, such
for locating, managing, administering, and organizing as software deployment, inventory, and object
common items and network resources. These can include management sharing and delegation (such as for user
volumes, folders, files, printers, users, groups, devices, accounts).
telephone numbers and other objects. A directory service 7 Single Group Policy container (GPC): With a single
is a solution which offers users access to the information GPC, management polices need to be defined only
stored in the directory through a well-defined interface. If a once, and can be used throughout the entire enterprise
network is used, an appropriate protocol has to be defined without the need to manually export and import Group
for this purpose. The Light weight Directory Access Policy Objects (GPOs).
Protocol(LDAP) is such a protocol.
8 Backup and recovery: Having only a single domain
Benefits of using directory services: means better resiliency because every location has a
full domain backup.
1 Resource management: The Network Administrator 9 Less hardware: In an organization with multiple
may use a single tool to manage network resources-- domains, every location needs two domain controllers
user accounts, servers, drives, files, printers, etc. These (DCs). With a single domain, each location needs only
are displayed in a simple tree structure, so they are a single DC because if the local DC fails, the locations
easy to locate and manage. Within this structure, each can use hub DCs. Reduced hardware also means fewer
resource is displayed by an icon called an object. By licenses, less management software, and less overhead
selecting an object, its settings are available, and the for server management. There's also no need to back
Network Administrator may modify them as he sees up remote DCs because the remote DCs just hold the
fit. same information as the central DCs-assuming the DCs
2 Users: You may use a single log on to access resources only perform directory services.
to which you've been granted rights. Rather than having Implementations of directory services
to log in to every server or authenticate to every printer
or other device, the directory contains this information. Directory services were part of an Open Systems
You log on once and you can do whatever the Network Interconnection (OSI) initiative to get everyone in the
Administrator has allowed via rights granted to you. industry to agree to common network standards to provide

214

Copyright Free under CC BY Licence


multi-vendor interoperability. In the 1980s, the International Active Directory
Telecommunication Union (ITU) and the International
Organization for Sandardization (ISO) came up with a set • Active Directory (AD) is a directory service that
of standards - X.500, for directory services. The protocol Microsoft developed for Windows domain networks and
decided upon is the Light weight Directory Access is included in most Windows Server operating systems
Protocol, LDAP, which is based on the directory information as a set of processes and services.
services of X.500, but uses the TCP/IP stack and a string
encoding scheme of the X.500 protocol DAP. • An AD domain controller authenticates and authorizes
all users and computers in a Windows domain type
Among the LDAP/X.500 based implementations are: network-assigning and enforcing security policies for
all computers and installing or updating software. For
• Active Directory: Microsoft's modern directory service example, when a user logs into a computer that is part
for Windows, originating from the X.500 directory, of a Windows domain, Active Directory checks the
created for use in Exchange Server, first shipped with submitted password and determines whether the user
Windows 2000 Server and is supported by successive is a system administrator or normal user.[3]
versions of Windows.
• Active Directory makes use of Lightweight Directory
• Apache Directory Server: Directory service written Access Protocol (LDAP) versions 2 and 3, Microsoft's
in Java, supporting LDAP, Kerberos 5 and the Change version of Kerberos, and DNS.
Password Protocol. LDAPv3 certified. The Apache
Directory Server is also a top level project of the Apache • Active Directory also makes user management easier
Software Foundation. as it acts as a single repository for all of this user and
computer related information.
• eDirectory: This is NetIQ's implementation of directory
services. It supports multiple architectures including • AD uses LDAP as its access protocol.
Windows, NetWare, Linux and several flavours of Unix
and has long been used for user administration, • AD relies on DNS as its locator service, enabling clients
configuration management, and software management. to locate domain controllers through DNS queries.
eDirectory has evolved into a central component in a Logical Structure of Active Directory
broader range of Identity management products. It was
previously known as Novell Directory Services. Active Directory is a distributed database that stores and
• Red Hat Directory Server: Red Hat released a manages information about network resources, as well as
directory service, that it acquired from AOL's Netscape application-specific data from directory enabled
Security Solutions unit, as a commercial product applications.
running on top of Red Hat Enterprise Linux called Red
Active Directory allows administrators to organize elements
Hat Directory Server and as the community supported
of a network (such as users, computers, devices, and so
389 Directory Server project.
on) into a hierarchical containment structure.
• Oracle Internet Directory: (OID) is Oracle
Corporation's directory service, which is compatible with In Active Directory, resources are organized in a logical
LDAP version 3. structure, and this grouping of resources logically enables
a resource to be found by its name rather than by its
• Sun Java System Directory Server: Sun
physical location.
Microsystems' current directory service offering.
• OpenDS: An open source directory service Benefits of AD Logical Structure
implementation from scratch in Java, backed by Sun
Microsystems. • Logical Structure provides more network security by
means of providing access to resources to only specified
• IBM Tivoli Directory Server: It is a customized build
groups (OU).
of an old release of OpenLDAP.
• Logical structure simplified the network management
• Windows NT Directory Services (NTDS), later
by administration, configuration and control of the
renamed Active Directory, replaces the former NT
network.
Domain system.
• The relationship between the logical structure of
• OpenLDAP : It supports all current computer
domains and forests simplifies resource sharing across
architectures, including Unix and Unix derivatives, Linux,
an organization.
Windows, z/OS, and a variety of embedded/realtime
systems. • As logical structure provides simplified network
management, it reduces the load on network resources
There are also plenty of open-source tools to create
and lower the total cost of ownership.
directory services, including OpenLDAP and the Kerberos
protocol, and Samba software.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.139 215

Copyright Free under CC BY Licence


Components of AD Logical Structure Within forests are domains. A domain is defined as a logical
group of network objects (computers, users, devices) that
The logical structure components have relationship with share the same active directory database.
each other so it manage to control access to stored data
and finds how the data will be managed between different Within domains are organizational units. OUs can provide
domains in a forest. hierarchy to a domain, ease its administration, and can
resemble the organization's structure in managerial or
• Objects: like a user, computer, group, printer etc… geographical terms. OUs can contain other OUs-domains
are containers in this sense. The OU is the level at which
• Organizational Units - like any folder but in control of
administrative powers are commonly delegated, but
Active Directory
delegation can be performed on individual objects or
• Domains - Logical boundaries for objects attributes as well.
• Trees - Logical boundary for multiple domains
This is called the logical model because it is independent
• Forests - Logical boundary for multiple trees of the physical aspects of the deployment, such as the
Overall, one physical machine running as a Microsoft number of domain controllers required within each domain
Domain controller can control all these logical divisions and network topology.
with the help of 'A Operation Master' dedicated to perform
specific tasks. Figure 1 shows the relationship between forests, domains,
and organizational units.
The top-level container is the forest. A forest is a collection
of trees that share a common global catalog, directory Figure 1 Relationship between Active Directory Forests,
schema, logical structure, and directory configuration. The Domains, and Organizational Units(OUs)
forest represents the security boundary within which users,
computers, groups, and other objects are accessible.

Fig 1

Relationship between Active Directory Forests, Domains, and Organizational Units (OUs)

The Physical Structure of an Active Directory The physical structure of Active Directory:

The Active Directory physical structure checks when and • Domain Controllers: These computers run Microsoft
where logon and replication traffic occurs. The physical Windows Server 2003/2000, and Active Directory. Every
structure of Active Directory contains all the physical Domain Controller performs specific functions like
subnets present in network like domain controllers and replication, storage and authentication. It can support
replication between domain controllers. maximum one domain. It is always advised to have
more than one domain controller in each domain.

216 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.139

Copyright Free under CC BY Licence


• Active Directory Sites: These sites are collection of OUs can be structured to allow for separate departments
well-connected computers. The reason why we create to have various levels of administrative control over their
site is domain controllers can communicate frequently own users. For example, a secretary in the Engineering
within the site. This way it minimizes the latency within department can be delegated control of resetting
site say changes made on one domain controller to be passwords for users within his own OU. Another advantage
replicated to other domain controllers. The other reason of OU use in these situations is that users can be easily
behind creating a site is to optimize bandwidth between dragged and dropped from one OU to another. For example,
domain controllers which are located in different if users are moved from one department to another, moving
locations. them into their new department's OU is extremely simple.

All IP subnets who share the common Local Area Network It is important to keep in mind that OU structure can be
(LAN) connectivity without knowing the actual physical modified on the fly any time an administrator feels fit to
location of computers is called site. make structural changes. This gives Active Directory the
added advantage of making changes any time.
A global catalog is a data storage source containing partial
representations of objects found in a multidomain Active Group Policy is a feature of the Microsoft Windows NT
Directory Domain Services (ADDS) forest. The global family of operating systems that control the working
catalog is stored on domain controllers specifically environment of user accounts and computer accounts.
assigned as global catalog servers. It can locate objects Group Policy provides the centralized management and
in any domain without knowing the actual domain name. configuration of operating systems, applications, and users'
settings in an Active Directory environment. A version of
Searches that are directed to the global catalog are faster Group Policy called Local Group Policy ("LGPO" or
because they do not involve referrals to different domain "LocalGPO") also allows Group Policy Object management
controllers. on standalone and non-domain computers. Group Policy
is one of the top reasons to deploy Active Directory
Organizing resources in OU because it allows you to manage user and computer
objects.
OUs are the primary method for organizing user, computer,
and other object information into a more easily Group Policy, in part, controls what users can and cannot
understandable layout. The organization has a root do on a computer system, for example: to enforce a
organizational unit where three nested organizational units password complexity policy that prevents users from
are placed. This nesting enables the organization to choosing an overly simple password, to allow or prevent
distribute users across multiple containers for easier unidentified users from remote computers to connect to a
viewing and administration of network resources. network share, to block access to the Windows Task
Manager or to restrict access to certain folders. A set of
OUs can be further sub divided into resource OUs for easy such configurations is called a Group Policy Object (GPO).
organization and delegation of administration. Far-flung
offices could have their own OUs for local administration Active Directory Backup and Restore
as well. It is important to understand, however, that an OU
should be created only if the organization has a specific Active Directory is one of the most critical components of
need to delegate administration to another set of your infrastructure. If it goes down, your network is
administrators. If the same person or group of people rendered useless. Therefore, to ensure business continuity
administer the entire domain, there is no need to increase and compliance, you need to have a solid backup and
the complexity of the environment by adding OUs. In fact, recovery plan in place for Active Directory.
too many OUs can impact group policies, logons, and
other factors. Where a Group Policy Preference Settings is configured
and there is also an equivalent Group Policy Setting
configured, then the value of the Group Policy Setting will
take precedence. group policy is security of
domain.Backup utility will automatically locate and include
them when you back up system state.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.139 217

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.5.140
COPA - Cyber Security

Access Control, Audit and testing


Objectives: At the end of this lesson you shall be able to
• describe the purpose and steps in access control
• describe the various layers in access control
• describe the access control mechanisms
• classify information for security
• list the access control protocols
• describe security audit
• describe the important of security audits
• describe the process of performing audit security
• describe vulnerability assessment and penetration testing
• mention the various types of security audit tools.
Introduction Authorization : After a person, program or computer has
successfully been identified and authenticated then it must
Access to protected information must be restricted to be determined what informational resources they are
people who are authorized to access the information. The permitted to access and what actions they will be allowed
purpose of Access Control is to limit the actions or to perform (run, view, create, delete, or change). This is
operations that a legitimate user of a computer system called Authorization. Authorization to access information
can perform, as well as what programs executing on behalf and other computing services begins with administrative
of the users are allowed to do. In this way access control policies and procedures. The policies prescribe what
seeks to prevent activity that could lead to a breach of information and computing services can be accessed, by
security. whom, and under what conditions.

The sophistication of the access control mechanisms Authentication Methods


should be proportional to the value of the information being
protected - the more sensitive or valuable the information • The risk of eavesdropping can be managed by using
the stronger the control mechanisms need to be. The digests for authentication. The connecting party sends
foundation on which access control mechanisms are built a value, typically a hash of the client IP address, time
start with identification and authentication. stamp, and additional secret information. Because this
hash is unique for each accessed URI, no other
Access control is generally achieved in three steps: documents can be accessed nor can it not be used
Identification, Authentication, and Authorization. from other IP address without detection. The password
is also not vulnerable to eavesdropping because of the
• Identification is an assertion of who someone is or what hashing. The system is, however, vulnerable to active
something is. A user identifies himself by entering by attacks such as the -man-in-the middle attack.
entering that username.
• One-time passwords: To avoid the problems associated
• Authentication is the process of verifying the user's with password reuse, one-time passwords were
identity. Authentication is one of the five pillars of developed. There are two types of one-time passwords,
information assurance (IA). The other four are integrity, a challenge-response password and a password list.
availability, confidentiality and nonrepudiation. • Public -key cryptography: Public key cryptography is
based on very complex mathematical problems that
Entering the password is a common method for
require very specialized knowledge. Public key
authentication. But password-based authentication is not
cryptography makes use of two keys, one private and
suitable for use on computer networks. Passwords sent
the other public. The two keys are linked together by
across the networks can be intercepted and subsequently
way of an extremely complex mathematical equation.
misused by hackers. In addition to the security concern,
The private key is used to decrypt and also to encrypt
password based authentication is inconvenient as the user
messages between the communicating machines. Both
has to enter the password each time the network service
encryption and verification of signature is accomplished
is to be accessed. The weakness in this system for
with the public key.
transactions that are significant (such as the exchange of
money) is that passwords can often be stolen, accidentally • Zero -knowledge proofs: Zero-knowledge proofs make
revealed, or forgotten. it possible for a Host to convince another Host to allow
access without revealing any "secret information". The
hosts involved in this form of authentication usually
communicate several times to finalize authentication.

218

Copyright Free under CC BY Licence


• Use of digital certificates issued and verified by a The next four layers are part of Oracle User Management:
Certificate Authority (CA) as part of a public key
infrastructure is considered another standard way to • Role-Based Access Control
perform authentication on the Internet. • Delegated Administration
• Another method of authentication, biometrics, depends • Registration Processes
on the user's presence and biological makeup (i.e.,
retina or fingerprints). This technology makes it more • Self Service and Approvals
difficult for hackers to break into computer systems.
Using special protocols for authentication like Secure In general, Access Control with begins with basic system
Sockets Layer (SSL), IP SEC, Secure Shell (SSH), administration tasks, progresses to more distributed, local
Kerberos authentication and Extensible Authentication modes of administration, and ultimately enables users to
Protocol (EAP) etc. perform some basic, predefined registration tasks on their
own. Table 1. illustrates how the layers build upon each
A security administrator maintains a database of other.
authorizations based on the security policy of the
organization. The reference monitor consults an Table 1
authorization database in order to determine if the user
attempting to do an operation is actually authorized to Layer of Access Level of
perform that operation. Auditing monitors and keeps a Administration
record of relevant activity in the system.
Self Service and Approvals End Users
It is important to make a clear distinction between
authentication and access control. Correctly establishing Registration Processes
the identity of the user is the responsibility of the
authentication service. Access control assumes that the Delegated Administration Local Administration
authentication of the user has been successfully verified
prior to enforcement of access control via a reference Role Based Access Control
monitor.
Data Security System Administrator
Successive Layers of Access Control
Function Security
Access Control is implemented in successive layers and
each layer builds upon the one that precedes it. The Security and Data Security mechanisms constitute
Organizations can, optionally, uptake the various layers the base layers of the security system, and contain the
depending on the degree of automation and scalability traditional system administrative capabilities. They limit
they wish to build upon the existing Function and Data the scope of User Management to basic system
Security models. There can be various models to administration by granting access to specific menus.
implement this. As an example, the Oracle User
Management has six layers of access control. Local Administrators
(Refer Fig 1) The Core Security layers include:
When Role-Based Access Control and Delegated
Fig 1 Administration are added to the Data Security and Function
1 Self Service and Approvals Security layers, system administration tasks can be
distributed to local administrators who manage a subset
2 Registraon Processes of the organization's users.
Oponal

3 Delegated Administraon End Users

Registration Processes and Self Service and Approvals


4 Role Based Access Control distribute system administration further by automating
some registration tasks so that end users can perform
5 Data Security them. End users can perform the tasks of Obtaining new
Required

User Accounts, Request additional access to the system


6 Funcon Security
and reset passwords.

Self Service and Approvals

• Function Security After the registration processes have been configured as


per requirements, individuals can subsequently perform
• Data Security self-service registration tasks, such as obtaining new user
accounts or requesting additional access to the system.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140 219

Copyright Free under CC BY Licence


In addition, organizations can use the Oracle Approvals role. The user does not have a control over the role that he
Management engine to create customized approval routing will be assigned.
for these requests.
• Discretionary Access Control (DAC)
There are three types of Preventive controls :
As the name suggests, this access control model is based
Administrative controls on a user's discretion. i.e, the owner of the resource can
give access rights on that resource to other users based
• Policies/Procedures: to identify the ways in which on his discretion. Access Control Lists (ACLs) are a typical
processes must be performed. This must go hand in example of DAC. Specifying the "rwx" permissions on a
hand with training, detective controls and audits. Unix file owned by you is another example of DAC Most of
the operating systems including windows, flavours of Unix
Physical Controls
are based on DAC Model.
• Using Biometric sensors, Smart cards etc.
• Mandatory Access Control (MAC)
Technical (Logical)Controls
In this Model, users/owners do not enjoy the privilege of
• Encryption deciding who can access their files. Here the operating
system is the decision maker overriding the user's wishes.
• Passwords and Tokens In this model every Subject (users) and Object (resources)
• Biometrics are classified and assigned with a security label. The
security labels of the subject and the object along with
• O.S. and Application Controls the security policy determine if the subject can access
• Identification and Authorization Technologies the object. The rules for how subjects access objects are
made by the security officer, configured by the
Access Control Mechanisms administrator, enforced by the operating system, and
supported by security technologies.
The following are the models/mechanisms for access
control. Each of the above Access Models has its own This is a stricter and rather static Access Control model
advantages and disadvantages. The selection of the as compared to DAC and is mostly suited for military
appropriate Access Model by an organization should be organizations where data classification and confidentiality
done by considering various factors such as type of is of prime importance. Special types of the Unix operating
business, no of users, organization's security policy etc. systems are based on MAC model.

Table 2 • Attribute Based Access Control (ABAC)

Control Service Description This is to grant or deny user requests based on arbitrary
attributes of the user,arbitrary attributes of the object, and
Preventive Keep Undesirable Things from environment conditions that may be more relevant to the
Happening policies at hand.

Detective Identify Undesirable things that Password Cracking Methods And Their
have taken place Countermeasures:

Corrective Correct Undesirable things that There are number of methods used by hackers to hack
have taken place the accounts or steal personal information. Some of the
most commonly used methods to crack passwords and
Deterrent Discourage Security Violations their counter measures are as follows:
from taking place
1 BruteForce Attack
Recovery Restore Resources or Capabilities
after a Violation or Accident Any password can be cracked using Brute-force attack.
Brute-force attacks try every possible combinations of
Compensation Provide Alternatives to other numbers, letters and special characters until the right
Controls password is match. Brute- force attacks can take very
long time depending upon the complexity of the password.
• Role Based Access Control (RBAC) depending on the speed of computer and complexity of
the password.
Access decisions are based on an individual's roles and
responsibilities within the organization or user base. RBAC Countermeasure: Use long and complex passwords. Try
is also known as non-discretionary Access Control to use combination of upper and lowercase letters along
because the user inherits privileges that are tied to his

220 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140

Copyright Free under CC BY Licence


with numbers. Brute-force attack will take very long time 6 Guessing:
to crack such complex and long passwords. You may
even keep changing the passwords frequently. This is a simple method to help you get someone's
password within seconds. If hacker knows you, he can
2 Social Engineering use information he knows about you to guess your
password. Hacker can also use combination of Social
Social engineering is process of manipulating someone Engineering and Guessing to acquire your password.
to trust you and get information from them. For example,
f the hacker was trying to get the password of a co-workers Counter measure: Don't use your name, surname, phone
or friends computer, he could call him pretending to be number or birth date as your password. Try to avoid creating
from the IT department or a bank and simply ask for his password that relates to you. Create complex and long
login or credit card details. password with combination of letters and numbers.

Countermeasure: Never ever give your sensitive Security classification for information
information like credit card details on phone.
Not all information is equal and so not all information
3 Rats And Keyloggers: requires the same degree of protection. This requires
information to be assigned a security classification.
In keylogging or rating the hacker sends keylogger or
Rat to the victim. This allows hacker to monitor everything
The first step in information classification is to identify a
victim do on his computer. Every keystroke is logged
member of senior management as the owner of the
including passwords. Moreover hacker can even control
particular information to be classified. Next, develop a
the victim's computer too.
classification policy. The policy should be able to:
Countermeasure: Never login to your bank account from
• Storing information
the cyber cafe or someone else’s computer. If it is very
important, use on-screen or virtual keyboard while tying • Transmitting information
the login. Use latest anti-virus software and keep the • Describe different classification labels,
definitions updated.
• Define the criteria for information to be assigned a
4 Phishing: particular label, and
• List the required security controls for each
Phishing is the most easiest and popular hacking method
classification.
used by hackers to get someone account details. In
Phishing attack hacker send fakepage of real website like • Disposing of unneeded information
facebook, gmail to victim. When someone logs in through • Protecting the integrity of information
that fake page his details is sent to the hacker. This fake
pages can be easily created and hosted on free web- • Allowing appropriate access and disclosure
hosting sites. • Establishing accountability.
Countermeasure: Phishing attacks are very easy to avoid. Some factors that influence which classification information
The url of this phishing pages are different from the real should be assigned include:
one. For example URL of phishing page of facebook might
look like facbbook.com (As you can see There are two • How much value that information has to the organization
"b"). Always make sure that websites url is correct. • How old the information is and
5 Rainbow Table: • Whether or not the information has become obsolete.
• Laws and other regulatory requirements
A Rainbow table is a huge pre- computed list of hashes for
every possible combination of characters. A password hash The Business Model for Information Security enables
is a password that has gone through a mathematical security professionals to examine security from systems
algorithm such as md5 and is transformed into something perspective, creating an environment where security can
which is not recognizable. A hash is a one way encryption be managed holistically, allowing actual risks to be
so once a password is hashed there is no way to get the addressed.
original string from the hashed string.
The type of information security classification labels
Countermeasure: Make sure you choose password that selected and used will depend on the nature of the
is long and complex. Creating tables for long and complex organization, with examples being:
password takes a very long time and a lot of resources.
• In the business sector, labels such as: Public,
Sensitive, Private and Confidential.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140 221

Copyright Free under CC BY Licence


• In the government sector, labels such as: Unclassified, Diameter
Sensitive But Unclassified, Restricted, Confidential,
Secret, Top Secret and their non-English equivalents. Diameter is an authentication, authorization, and
accounting protocol for computer networks. It evolved from
• In cross-sectoral formations, the Traffic Light Protocol,
and replaces the much less capable RADIUS protocol
which consists of: White, Green, Amber, and Red.
that preceded it. Diameter Applications extend the base
protocol by adding new commands and/or attributes. It
All employees in the organization, as well as business
provides better, better transport, better security, better
partners, must be trained on the classification scheme
proxying, better session control and better interoperability
and understand the required security controls and handling
when compared to RADIUS.
procedures for each classification. The classification of a
particular information asset that has been assigned should
TACACS
be reviewed periodically to ensure the classification is still
appropriate for the information and to ensure the security
Terminal Access Controller Access-Control System
controls required by the classification are in place.
(TACACS, usually pronounced like tack-axe) refers to a
family of related protocols handling remote authentication
Declassifying and downgrading
and related services for networked access control through
a centralized server. The original TACACS protocol, which
Information must be classified or designated only for the
dates back to 1984, was used for communicating with an
time it requires protection, after which it is to be declassified
authentication server, common in older UNIX networks.
or downgraded. This is because the classified or
Extended TACACS (XTACACS) is a proprietary extension
designated information will lose its sensitivity with the
to TACACS introduced by Cisco Systems in 1990 without
passage of time or the occurrence of specific events. This
backwards compatibility to the original protocol. Terminal
process contributes to the overall integrity of the security
Access Controller Access-Control System Plus
system, and ensures that information is made available
(TACACS+) is a protocol developed by Cisco and released
quickly and informally to interested members of the public.
as an open standard beginning in 1993.
Access Control Administration
Decentralized Access Control
Access control administration can be done in two ways.
• A decentralized access control administration method
• Centralized : Here one entity (dept or an individual) is gives control of access to the people closer to the
responsible for overseeing access to all corporate resources
resources. This type of administration provides a • In this approach, it is often the functional manager who
consistent and uniform method of controlling users assigns access control rights to employees.
access rights. Example: RADIUS, TACACS and
• Changes can happen faster through this type of
Diameter
administration because not just one entity is making
• Decentralized changes for the whole organization.
Access Control / Data Collection Protocols: AAA (RADIUS, • There is a possibility for conflicts to arise that may not
Diameter, and TACACS+) benefit the organization as because different managers
and departments can practice security and access
RADIUS, Diameter, and TACACS+ are three protocols for control in different ways.
carrying Authentication, Authorization, and Accounting
• There is a possibility of certain controls to overlap, in
(AAA) information between a Network Access Server
which case actions may not be properly proscribed or
(NAS) that wants to authenticate its links or end users.
restricted.
RADIUS • This type of administration does not provide methods
for consistent control, as a centralized method would.
The Remote Authentication Dial-In User Service (RADIUS)
is a client/server security protocol created by Lucent A Security Audit is essentially an assessment of how
InterNetworking Systems. RADIUS is an Internet draft effectively the organization's security policy is being
standard protocol. User profiles are stored in a central implemented. It is an independent review and examination
location, known as the RADIUS server. RADIUS clients of an IT system's policy, records, and activities.
(such as a PortMaster communications server)
communicate with the RADIUS server to authenticate Information systems audit is important because it gives
users. The server specifies back to the client what the assurance that the IT systems are adequately protected,
authenticated user is authorized to do. Although the term provide reliable information to users, and are properly
RADIUS refers to the network protocol that the client and managed to achieve their intended benefits. It also reduces
server use to communicate, it is often used to refer to the the risk data tampering, data loss or leakage, service
entire client/server system. disruption and poor management of IT systems.

222 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140

Copyright Free under CC BY Licence


As Security Auditing and Testing (SAT) helps an Generally, computer security audits are performed by:
organization to understand the state of security for internal
reasons and provides assurance to external parties, it 1 Federal or State Regulators.
requires an attention of the highest degree. It helps to 2 Corporate Internal Auditors.
identify the gaps in the existing defenses.
3 External Auditors - Specialized in the areas related to
Establishing audit objectives technology auditing.
4 Consultants - Outsourcing the technology auditing
After planning an Audit and before proceeding to perform
where the organization lacks the specialized skill set.
the audit, one should establish the audit objectives.
Following is a list of objectives the auditor should review: First, the audit's scope should be decided and include all
company assets related to information security, including
• Personnel procedures and responsibilities including computer equipment, phones, network, email, data and
systems and cross-functional training any access-related items, such as cards, tokens and
passwords. Then, past and potential future asset threats
• Change management processes are in place and
must be reviewed. Anyone in the information security field
followed by IT and management personnel. Change
should stay apprised of new trends, as well as security
Management refers to the efficient and prompt handling
measures taken by other companies. Next, the auditing
of all changes to control IT infrastructure, in order to
team should estimate the amount of destruction that could
minimize the number and impact of any related
transpire under threatening conditions. There should be
incidents upon service.
an established plan and controls for maintaining business
• Appropriate back up procedures are in place to operations after a threat has occurred, which is called an
minimize downtime and prevent loss of important data intrusion prevention system.
• The data center has adequate physical security controls
Performing the review
to prevent unauthorized access to the data center
• Adequate environmental controls are in place to ensure The next step is collecting evidence to satisfy data center
equipment is protected from fire and flooding. audit objectives. This involves traveling to the data center
location and observing processes and procedures
Audit planning & preparation performed within the data center. The following review
procedures should be conducted to satisfy the pre-
The auditor should be adequately educated about the determined audit objectives:
company and its critical business activities before
conducting a data center review. The auditor should perform • The auditor should observe and interview data center
the following before conducting the review: employees to satisfy their objectives.
• The auditor should verify that all data center equipment
• Meet with IT management to determine possible areas
is working properly and effectively.
of concern
• All data center policies and procedures should be
• Review the current IT organization chart
documented and located at the data center. Important
• Review job descriptions of data center employees documented procedures include: data center personnel
• Research all operating systems, software applications job responsibilities, back up policies, security policies,
and data center equipment operating within the data employee termination policies, system operating
center procedures and an overview of operating systems.

• Review the company's IT policies and procedures • The auditor should assess the security of the client's
data center with respect to physical security controls
• Evaluate the company's IT budget and systems and environmental controls should be in place to ensure
planning documentation the security of data center equipment. These include:
• Review the data center's disaster recovery plan. Air conditioning units, raised floors, humidifiers and
uninterruptible power supply.
Performing an Audit • Backup procedures - The auditor should verify that the
client has backup procedures in place in the case of
There is no standard security-audit process, but auditors system failure. Clients may maintain a backup data
typically accomplish their job though personal interviews, center at a separate location that allows them to
vulnerability scans, examination of OS and security- instantaneously continue operations in the instance of
application settings, and network analyses, as well as by system failure.
studying historical data such as event logs. Auditors also
focus on the business's security policies to determine what
they cover, how they are used and whether they are effective
at meeting ongoing and future threats.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140 223

Copyright Free under CC BY Licence


Penetration Tests, Vulnerability Assessments And Access Control and Auditing
Security Audits
Physical and logical security
External Attackers often make use of already known
vulnerabilities and exploits in order to infiltrate in systems
There are multiple types of security, physical and logical.
and network. Taking appropriate defensive measures and
Physical security involves things like locks or biometrics.
adequate security design can mitigate this problem. This
Logical security examples consist of software safeguards
can also be achieved to a good extent by the recognizing
including access control and auditing, user account
already existing exposed systems and their risks at regular
management, violation and security activity reports, and
intervals. The risks may be detected in the earlier stages
firewalls.
and appropriate measures can be taken at an earlier stage.
Access control is a system enabling authorities to control
Vulnerability assessment is a practice used to identify all
access to areas and resources in a given physical facility
potential vulnerabilities that could be exploited in an
or computer-based information system. The Password for
environment. The assessment can be used to evaluate
a computer or PIN of an ATM system are forms of access
physical security, personnel, or system and network
control. Using an access control mechanism is important
security. Vulnerability identification tools may be used to
when persons seek to secure confidential, important, or
identify them. A list of every computer system by IP address
sensitive information and equipment.
and their associated vulnerabilities and steps on how to
"fix" the vulnerabilities should then be generated. Auditing an Access Control System is a way of tracking
Penetration test is carried out with the motive of "breaking the occurrence of entrance or attempted entrance into a
into the network" using the known vulnerabilities. From system. This is important because it shows how
here, the aim is to gain administrator or root access on successful the access control system is, as well as who
the most critical system in the network. This gives was denied access, and if they attempt entrance more
complete access to the network to tamper with or modify than once, what is their intention?
the systems and the data on the systems. A penetration
test is carried out to emulate what a real hacker would do Logical Audit is done to check the following:
and it proves to the company that the organization can
indeed be penetrated. • Strengths and weaknesses of Access Violations
• Security Activity Reports
Penetration testing is also referred to as ethical hacking.
In most cases, the security professional can look at reports • Logging activity reports
from a vulnerability scanner and understand the level of • Efficiency of firewalls
risk the company is facing.
• Reports on violations of security
Audit Controls • Reports of Attempts by unauthorized persons to hack
the system etc.
Review of Application Controls - It is the identification of
the risks of deployed technology and minimization of the Professional Ethics for Auditors
company's exposure to such risks, by ensuring that the
necessary controls and security are in place. To gain trust in an objective audit, it is necessary to uphold
a set of professional ethics. The professional ethics must
Review of General Computer Controls - It is done for be upheld by individual persons as well as by companies
providing a secure and stable environment for the providing services in the field of Information Security
application systems running on various platforms within Auditing. The professional ethics consist of the following
the company. principles:

system may be lost if errors are found in operational Honesty and confidentiality
systems
Honesty is the foundation of trust and forms the basis for
Objectives Of Controls the reliability of an assessment. Since sensitive business
processes and information are often found to be dependent
• To make sure data entering the computer are correct on information security, the confidentiality of the information
obtained during an audit and the discreet handling of the
• Check clerical handling of data before it is input to a results and findings of the IS audit are an important basis
computer for such work. IS auditors are aware of the value of the
• Provide means of detecting and tracing errors which information they receive and who owns it, and will not
occur due to bad data or bad program disclose this information without the corresponding
permission unless they are legally or professionally
• Ensure legal requirements are met required to do so.
• To guard against frauds

224 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140

Copyright Free under CC BY Licence


Expert knowledge Information in an organization needs to be secured properly
against the consequences of breaches of confidentiality,
IS auditors only accept those jobs for which they have the integrity and availability. Proper security measures need
requisite knowledge and skills as well as the corresponding to be implemented to control and secure information from
experience and use these when performing their task. They unauthorized changes, deletions and disclosures. To find
continuously improve their knowledge as well as the the level of security measures that need to be applied, a
effectiveness and quality of their work. risk assessment is mandatory.

Objectivity and thoroughness Security policies are intended to define what is expected
from employees within an organization with respect to
An IS auditor must demonstrate the highest possible level information systems. The objective is to guide or control
of expert objectivity and thoroughness when collecting, the use of systems to reduce the risk to information assets.
evaluating, and passing on information on the activities or It also gives the staff who are dealing with information
business processes audited. The evaluation of all relevant systems an acceptable use policy, explaining what is
circumstances must be performed impartially and may allowed and what not. Security policies of all companies
not be influenced by the auditor's own interests or the are not same, but the key motive behind them is to protect
interests of others. assets. Security policies are designed with specific goals.

Objective presentation Information Security Audit Tools

An IS auditor has the duty to report the results of the Information Security Audit Tools include utilities and power
examination precisely and truthfully to his client. This tools, both open source and commercial.
includes the impartial and understandable presentation of
the facts in the IS audit reports, the constructive evaluation Utility Tools : These are single-purpose tools that may
of the facts determined, and specific recommendations either be native to the operating system or freely available.
for improving the safeguards and processes. Utility tools require a manual approach, though they are
often included in customized scripts--or even commercial
Verifications and reproducibility products. You may even include native utilities, such as
ping available on most platforms, used to determine if a
The rational basis for reliable and comprehensible network target responds to ICMP packets.
conclusions and results is the clear and consistent
documentation of the actual facts. This also includes that Pros: Utility tools are freely available and are tightly focused
the IS audit team follows a documented and reproducible for a specific task, making them more efficient. They help
methodology to come to its conclusions. in discovering vulnerabilities much faster than those found
manually.
Compliance audit
Cons: It requires skill to use them. For a large audit, manual
A compliance audit is a comprehensive review of an testing is time-consuming and may produce inconsistent
organization's adherence to regulatory guidelines. results, depending on the skill of the auditor.
Independent accounting, security or IT consultants evaluate
the strength and thoroughness of compliance preparations. Traceroute: A network tracing utility used to determine
Auditors review security polices, user access controls and the network route to a host.
risk management procedures over the course of a
compliance audit. nslookup: used to determine domain ownership.

What is examined in a compliance audit will vary And open-source scripts, including:
depending upon whether an organization is a public or
private company, what kind of data it handles and if it Nmap: Free port-scanning utility.
transmits or stores sensitive financial data.
Crack: Popular password-cracking tool used to determine
Information Security Policies if passwords are weak by attempting to break them.

Organizations are giving more priority to development of John the Ripper: A password-cracking tool used primarily
information security policies, as protecting their assets is to discover Unix passwords.
one of the prominent things that needs to be considered.
Lack of clarity in information security policies can lead to binfo.c: A BIND version checker, binfo is a quick little
severe damages which cannot be recovered. So an script to pull back the version of named running on a remote
organization makes different strategies in implementing a name server.
security policy successfully. An information security policy
provides management direction and support for information ghba.c: A handy tool for extracting all the machine names
security across the organization. and IP addresses of a given class B or C subnet.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140 225

Copyright Free under CC BY Licence


Power Tools Google

Power Tools are multi-function bundled utilities to streamline A real hacker thinks outside the box and learns to use
and automate parts of the audit process. While some are tools in a way they may not have been intended. While
open-source packages, many are commercial products the Google search engine is not, strictly speaking, an
with custom vulnerability databases. auditing tool, it's great for gathering information about a
site. For example, trying entering "@DGET.com" (where
Pros: Automated tools scan for vulnerabilities against a "DGET" is your domain). Sometimes, this can yield some
database. Alerts may be tied into help desk monitoring good data, such as a system administrator posting
tools. In some cases, a scanning tool may be integrated technical details about his site, which conveniently
with a firewall or intrusion detection management station. contains his account name. Google is like the Unix "grep"
Some commercial scanners produce excellent reports command on steroids.
detailing exposures and associated risk.
Communicating Results
Cons: Scanners only check for vulnerabilities in their
database, which must be current. Many scanners are A final item to be considered is how to communicate with
marketed on the number of vulnerability checks performed. auditees, ie. the persons whose assets are being audited.
This isn't always a good indication of the tool's When informing auditees of continuous audit activity
effectiveness. Often, vulnerabilities are misdiagnosed. A results, it is important for the exchange to be independent
scanner can't accurately assess risk. and consistent.

Some of the Open-source power tools are Nessus, Reporting to senior management on defined
SARA(The Security Auditor's Research Assistant), parameters
Whisker, etc. among many others.
A typical audit report to the management and the
Some of the commercial scanners available today are management's response may look like the one shown in
Internet Security System's Internet Scanner, eEye Digital Table 1 below, but there are many other formats of the
Security's Retina, BindView's BV-Control, CORE Security reports and Reponses in use.
Technology's Auditing Tools Suite and Foundstone's
FoundScan.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140
226

Copyright Free under CC BY Licence


Table 1

Sl. No, Findings Impacts Recommendations Management Action / TimeLimit


Response Plan

1 The organization The situtation The organization Person Responsible :


uses templates increases the should continue The chief information
to configure new risk of the documenting officer (CIO):The auditor’s
windows firewalls unauthorized configuration recommendations will No further
and servers, but access to the standard based be implemented. The action
does not have a organization’s on the technologies security team will required
documented systems in place. continue documenting
technology configuration standards
configuration especially for UNIX
standard for and LINUX O.S.
other technologies
such as DBMS,
UNIX and LINUX
operating systems
etc.

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.

3 We noted that This situation Person Responsible :


users are their increases the Remove The chief information
own workstation risk of the workstation officer. The situation
administrators, unauthorized administration was especially prevalanet November
so that they can access to the privileges. with windows 2000 with 1st 2014
deactivate their organization’s the latest servers users
workstation systems. It only have the privileges
antivirus and idle also increases to do their job. There
system the risk of are a few exceptions.
configurations. system failure The situation will be
remediated as we are
upgrading all our systems.

IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140 227

Copyright Free under CC BY Licence


IT & ITES Related Theory for Exercise 2.5.141
COPA - Cyber Securtiy

Privacy Protection and IT Act


Objectives: At the end of this lesson you shall be able to
• describe information privacy
• describe the method of protecting privacy in information systems
• describe the best online privacy practices
• explain about what is IT Act
• describe about cyber crimes.
Introduction Improper or non-existent disclosure control can be the
root cause for privacy issues. Data privacy issues can
Privacy is the ability of an individual or group to seclude arise in response to information from a wide range of
their systems, data or information and share it selectively. sources, such as:
When something is private to a person, it usually means
that it is something special or sensitive. • Health care records
• Investigations and proceedings
Information or data privacy refers to the evolving relationship
between technology and the legal right to, or public • Financial institutions and transactions
expectation of, privacy in the collection and sharing of
• Residence and geographic records
data about one's self. Privacy concerns exist wherever
uniquely identifiable data relating to a person or persons • Defence data
are collected and stored, in digital form or otherwise. In • Privacy breach
some cases these concerns refer to how data are collected,
stored, and associated. In other cases the issue is who is • Location-based service and geolocation
given access to information. Other issues include whether • Scientific research etc.
an individual has any ownership rights to data about them,
and/or the right to view, verify, and challenge that The challenge in data privacy is to share data while
information. protecting personally identifiable information. The fields of
data security and information security design and utilize
Information security keeps unauthorized persons or software, hardware and human resources to address this
systems from gaining access to restricted information. issue. As the laws and regulations related to Data
Privacy is the collection of rules and obligations that Protection are constantly changing, it is important to keep
determine how and when access is to be authorized, in abreast of any changes in the law and continually reassess
any medium. It follows that good security and privacy your compliance with data privacy and security regulations.
practices depend on one another. The domain of privacy
partially overlaps security, including for instance the Protecting privacy in information systems
concepts of appropriate use, as well as protection of
information. As a variety of information systems with differing privacy
rules are interconnected and information is shared, policy
The relationship between computer security and privacy appliances will be required to reconcile, enforce and monitor
lies in the fact that adequate computer security, or lack of an increasing amount of privacy policy rules (and laws).
it, is a determinant of the level of privacy that a computer There are two categories of technology to address privacy
user can expect. People use computers to perform many protection in commercial IT systems: communication and
tasks, including business, banking, socializing and storing enforcement.
of private information. If there is a breach of computer
security, it will have a negative effect on the way these Policy Communication P3P : This is the Platform for
types of tasks are carried out. Privacy Preferences. P3P is a standard for communicating
privacy practices and comparing them to the preferences
In the area of e-Commerce, the issue of computer security of individuals.
and privacy will determine the level of trust between the
business parties. If there is any suspicion of a breach of Policy Enforcement :
security on either side, this will lead to a destruction of
trust and an end to the business relationship. This includes • XACML - The Extensible Access Control Markup
risks and threats from third parties not even related to the Language together with its Privacy Profile is a standard
business partners. for expressing privacy policies in a machine-readable
language which a software system can use to enforce
the policy in enterprise IT systems.

228

Copyright Free under CC BY Licence


• EPAL - The Enterprise Privacy Authorization Language Visit only trusted websites. Use applications like Site
is very similar to XACML, but is not yet a standard. Advisor etc. to know about the site you are opening.While
websites today share more information, they also provide
• WS-Privacy - "Web Service Privacy" will be a
their users with great specificity and control over these
specification for communicating privacy policy in web
sharing activities. On many websites you'll find that you
services. For example, it may specify how privacy
can define your audience when you share personal
policy information can be embedded in the SOAP
information or content, whether it's an audience of one or
envelope of a web service message.
the entire public.
Protecting Privacy on the Internet
Email has remained largely unchanged in the last decade.
On the internet you almost always give away a lot of Methods of exploiting email, however, have evolved
information about yourself. Unencrypted e-mails can be significantly and protecting personal information in email
read by the administrators of the e-mail server where the environments has become more challenging. In the past
connection is not encrypted (no https). Also the internet decade hacking has become more effective and phishing
service provider and other parties sniffing the traffic of that techniques, more elaborate. Here are some strategies for
connection are able to know the contents. Furthermore, protecting your privacy when using email:
the same applies to any kind of traffic generated on the
internet (web browsing, instant messaging, ...) In order 1 Use a secondary, "spam" email address
not to give away too much personal information, e-mails
2 Use email service providers with strong security and
can be encrypted and browsing of webpages as well as
spam filters
other online activities can be done traceless via
anonymizers, or, in cases those are not trusted, by open 3 Exercise caution when opening emails
source distributed anonymizers, so called mix nets.
4 Recognize that email is evolving towards openness and
Renowned open-source mix nets are I2P - The Anonymous
interconnectivity
Network or tor.
5 Use strong passwords and remember to sign-out
Protect Your Privacy Best Online Privacy Practices
The following is a list of tips and guidelines to safeguard 1 Minimize personal information sharing
your privacy, personal information online and prevent fraud
and abuse while using the Internet. 2 Look for trustmarks on websites and verify their
authenticity
• Get New Passwords: Use different, strong passwords 3 Consider temporary credit card numbers when shopping
for each of your online accounts so if one is online
compromised the rest are safe. Strong passwords
contains letters, numbers, different cases, and 4 Use strong passwords and remember to sign-out
symbols. Check your password's strength here. 5 Change your passwords frequently.
• Close Old Online Accounts: Unused online accounts 6 Use anti-virus and anti-spyware protection
are a liability. Hackers could use them to infiltrate your
more important accounts . Get rid of them. 7 Take advantage of browser privacy enhancing
capabilities and options
• Reduce Your Friends List.
8 Update your Browser and other tools.
• Go Paperless: Do not keep sensitive data online or in
your mail accounts. Mobile Privacy
• Shred Sensitive Documents: Get rid of unwanted 1 On mobile devices your personal information is more
documents containing sensitive data. Dispose them likely to be compromised via device theft or loss - take
securely, using a shredder. appropriate precautions
2 Your mobile device may be aware of your location and
Browser Privacy may share that data with applications and advertisers
Modern browsers have an impressive array of privacy
enhancing capabilities and options. They can, for example, CYBER CRIME ACT
warn you before you visit suspicious or fraudulent websites
and can also allow you to surf the web without downloading In the era of cyber world as the usage of computers became
tracking files like cookies to your computer. Also, most more popular, there was expansion in the growth of
browsers can inform you when a website uses SSL, a technology as well, and the term ‘Cyber’ became more
security measure that encrypts your data. When a website familiar to the people. The evolution of Information
uses SSL a browser may indicate this to you by displaying Technology (IT) gave birth to the cyber space wherein
a padlock icon (typically located on the bottom bar of your internet provides equal opportunities to all the people to
browser) or by highlighting the website's name in the access any information, data storage, analyse etc. with
address bar in green.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.141 229

Copyright Free under CC BY Licence


the use of high technology. Due to increase in the number Cyber-Stalking
of netizens, misuse of technology in the cyberspace was
clutching up which gave birth to cyber crimes at the It means expressed or implied a physical threat that
domestic and international level as well. creates fear through the use to computer technology such
as internet, e-mail, phones, text messages, webcam,
Though the word Crime carries its general meaning as “a websites or videos.
legal wrong that can be followed by criminal proceedings
which may result into punishment” whereas Cyber Crime Dissemination of Obscene Material
may be “unlawful acts wherein the computer is either a
tool or target or both”. It includes Indecent exposure/ Pornography (basically child
pornography), hosting of web site containing these
The world 1st computer specific law was enacted in the prohibited materials. These obscene matters may cause
year 1970 by the German State of Hesse in the form of harm to the mind of the adolescent and tend to deprave or
‘Data Protection Act, 1970’ with the advancement of cyber corrupt their mind.
technology. With the emergence of technology the misuse
of technology has also expanded to its optimum level and Defamation:
then there arises a need of strict statutory laws to regulate
the criminal activities in the cyber world and to protect It is an act of imputing any person with intent to lower
technological advancement system. It is under these down the dignity of the person by hacking his mail account
circumstances Indian parliament passed its and sending some mails with using vulgar language to
“INFORMATION TECHNOLOGY ACT, 2000” on 17th oct unknown persons mail account.
to have its exhaustive law to deal with the technology in
the field of e-commerce, e-governance, e-banking as well Hacking
as penalties and punishments in the field of cyber crimes.
It means unauthorized control/access over computer
Cyber Crimes Actually system and act of hacking completely destroys the whole
data as well as computer programmes. Hackers usually
It could be hackers vandalizing your site, viewing hacks telecommunication and mobile network.
confidential information, stealing trade secrets or
intellectual property with the use of internet. It can also Cracking
include ‘denial of services’ and viruses attacks preventing
regular traffic from reaching your site. Cyber crimes are It is amongst the gravest cyber crimes known till date. It
not limited to outsiders except in case of viruses and with is a dreadful feeling to know that a stranger has broken
respect to security related cyber crimes that usually done into your computer systems without your knowledge and
by the employees of particular company who can easily consent and has tampered with precious confidential data
access the password and data storage of the company and information.
for their benefits. Cyber crimes also includes criminal
activities done with the use of computers which further E-Mail Spoofing
perpetuates crimes i.e. financial crimes, sale of illegal
articles, pornography, online gambling, intellectual property A spoofed e-mail may be said to be one, which
crime, e-mail, spoofing, forgery, cyber defamation, cyber misrepresents its origin. It shows it’s origin to be different
stalking, unauthorized access to Computer system, theft from which actually it originates.
of information contained in the electronic form, e-mail
SMS Spoofing:
bombing, physically damaging the computer system etc.
Spoofing is a blocking through spam which means the
Classifications Of Cyber Crimes: Cyber Crimes which
unwanted uninvited messages. Here a offender steals
are growing day by day, it is very difficult to find out what
identity of another in the form of mobile phone number and
is actually a cyber crime and what is the conventional
sending SMS via internet and receiver gets the SMS from
crime so to come out of this confusion, cyber crimes can
the mobile phone number of the victim. It is very serious
be classified under different categories which are as follows:
cyber crime against any individual.
Cyber Crimes against Persons:
Carding
There are certain offences which affects the personality of
individuals can be defined as: It means false ATM cards i.e. Debit and Credit cards used
by criminals for their monetary benefits through withdrawing
Harassment via E-Mails: It is very common type of money from the victim’s bank account mala-fidely. There
harassment through sending letters, attachments of files is always unauthorized use of ATM cards in this type of
& folders i.e. via e-mails. At present harassment is common cyber crimes.
as usage of social sites i.e. Facebook, Twitter etc.
increasing day by day.

230 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.141

Copyright Free under CC BY Licence


Cheating & Fraud Transmitting Virus: Viruses are programs that attach
themselves to a computer or a file and then circulate
It means the person who is doing the act of cyber crime themselves to other files and to other computers on a
i.e. stealing password and data storage has done it with network. They usually affect the data on a computer, either
having guilty mind which leads to fraud and cheating. by altering or deleting it. Worm attacks plays major role in
affecting the computerize system of the individuals.
Child Pornography
Cyber Trespass: It means to access someone’s computer
It involves the use of computer networks to create, without the right authorization of the owner and does not
distribute, or access materials that sexually exploit disturb, alter, misuse, or damage data or system by using
underage children. wireless internet connection.

Assault by Threat Internet Time Thefts: Basically, Internet time theft comes
under hacking. It is the use by an unauthorised person, of
Assault by Threat refers to threatening a person with fear the Internet hours paid for by another person. The person
for their lives or lives of their families through the use of a who gets access to someone else’s ISP user ID and
computer network i.e. E-mail, videos or phones. password, either by hacking or by gaining access to it by
illegal means, uses it to access the Internet without the
Crimes Against Persons Property: other person’s knowledge. You can identify time theft if
the Internet time has to be recharged often, despite
As there is rapid growth in the international trade where infrequent usage.
businesses and consumers are increasingly using
computers to create, transmit and to store information in Cybercrimes Against Government:
the electronic form instead of traditional paper documents.
There are certain offences done by group of persons
There are certain offences which affects persons property
intending to threaten the international governments by
which are as follows:
using internet facilities. It includes:
Intellectual Property Crimes Cyber Terrorism

Intellectual property consists of a bundle of rights. Any Cyber terrorism is a major burning issue in the domestic
unlawful act by which the owner is deprived completely or as well as global concern. The common form of these
partially of his rights is an offence. The common form of terrorist attacks on the Internet is by distributed denial of
IPR violation may be said to be software piracy, infringement service attacks, hate websites and hate e-mails, attacks
of copyright, trademark, patents, designs and service mark on sensitive computer networks etc. Cyber terrorism
violation, theft of computer source code, etc. activities endanger the sovereignty and integrity of the
nation.
Cyber Squatting
Cyber Warfare
It means where two persons claim for the same Domain
Name either by claiming that they had registered the name It refers to politically motivated hacking to conduct
first on by right of using it before the other or using sabotage and espionage. It is a form of information warfare
something similar to that previously. sometimes seen as analogous to conventional warfare
although this analogy is controversial for both its accuracy
Cyber Vandalism and its political motivation.

Vandalism means deliberately destroying or damaging Distribution of pirated software


property of another. Thus cyber vandalism means
destroying or damaging the data when a network service It means distributing pirated software from one computer
is stopped or disrupted. It may include within its purview to another intending to destroy the data and official records
any kind of physical harm done to the computer of any of the government.
person. These acts may take the form of the theft of a
computer, some part of a computer or a peripheral attached Possession of Unauthorized Information:
to the computer.
It is very easy to access any information by the terrorists
Hacking Computer System: Hacktivism attacks those with the aid of internet and to possess that information for
included Famous Twitter, blogging platform by unauthorized political, religious, social, ideological objectives.
access/control over the computer. Due to the hacking
activity there will be loss of data as well as computer. Also Cybercrimes Against Society at large:
research especially indicates that those attacks were not
mainly intended for financial gain too and to diminish the An unlawful act done with the intention of causing harm to
reputation of particular person or company. the cyberspace will affect large number of persons. These
offences includes:
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.141 231

Copyright Free under CC BY Licence


Child Pornography: It involves the use of computer Need of Cyber Law
networks to create, distribute, or access materials that
sexually exploit underage children. It also includes activities Information technology has spread throughout the world.
concerning indecent exposure and obscenity. The computer is used in each and every sector wherein
cyberspace provides equal opportunities to all for economic
Cyber Trafficking: It may be trafficking in drugs, human growth and human development. As the user of cyberspace
beings, arms weapons etc. which affects large number of grows increasingly diverse and the range of online
persons. Trafficking in the cyberspace is also a gravest interaction expands, there is expansion in the cyber crimes
crime. i.e. breach of online contracts, perpetration of online torts
and crimes etc. Due to these consequences there was
Online Gambling need to adopt a strict law by the cyber space authority to
regulate criminal activities relating to cyber and to provide
Online fraud and cheating is one of the most lucrative better administration of justice to the victim of cyber crime.
businesses that are growing today in the cyber space. In the modern cyber technology world it is very much
There are many cases that have come to light are those necessary to regulate cyber crimes and most importantly
pertaining to credit card crimes, contractual crimes, offering cyber law should be made stricter in the case of cyber
jobs, etc. terrorism and hackers

Financial Crimes Penalty For Damage To Computer System

This type of offence is common as there is rapid growth in According to the Section: 43 of ‘Information Technology
the users of networking sites and phone networking where Act, 2000’ whoever does any act of destroys, deletes,
culprit will try to attack by sending bogus mails or alters and disrupts or causes disruption of any computer
messages through internet. Ex: Using credit cards by with the intention of damaging of the whole data of the
obtaining password illegally. computer system without the permission of the owner of
the computer, shall be liable to pay fine upto 1crore to the
Forgery person so affected by way of remedy. According to the
Section:43A which is inserted by ‘Information
It means to deceive large number of persons by sending Technology(Amendment) Act, 2008’ where a body
threatening mails as online business transactions are corporate is maintaining and protecting the data of the
becoming the habitual need of today’s life style. persons as provided by the central government, if there is
any negligent act or failure in protecting the data/
Affects To Whom information then a body corporate shall be liable to pay
compensation to person so affected. And Section 66 deals
Cyber Crimes always affects the companies of any size with ‘hacking with computer system’ and provides for
because almost all the companies gain an online presence imprisonment up to 3 years or fine, which may extend up
and take advantage of the rapid gains in the technology to 2 years or both.
but greater attention to be given to its security risks. In
the modern cyber world cyber crimes is the major issue
which is affecting individual as well as society at large
too.

232 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.141

Copyright Free under CC BY Licence


 

Copyright Free under CC BY Licence


 

Copyright Free under CC BY Licence

You might also like