0% found this document useful (0 votes)
90 views153 pages

Visual Basic With SQL Server

It's all about computer

Uploaded by

openhero45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views153 pages

Visual Basic With SQL Server

It's all about computer

Uploaded by

openhero45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 153

PART 5

VISUAL BASIC
WITH
SQL SERVER

ALL RIGHTS RESERVED TO SVTI


Contents
Introduction to Visual Basic ....................................................................................................................................... 5
Capabilities of Visual Basic ................................................................................................................................. 5
Visual Basic Overview ........................................................................................................................................ 5
Features of Visual Basic ..................................................................................................................................... 5
Types of Visual Basic Projects ............................................................................................................................ 5
Rapid Application Development ........................................................................................................................ 6
RAD Problems .................................................................................................................................................... 6
Visual Basic Editions ........................................................................................................................................... 6
The Visual Basic IDE ........................................................................................................................................... 7
Managing the Workspace ................................................................................................................................ 12
VB Reference Resources .......................................................................................................................................... 13
Using the Integrated Documentation .............................................................................................................. 13
Microsoft Developer Network ......................................................................................................................... 14
Developing Data Entry Dialogs................................................................................................................................. 15
Dialogs .............................................................................................................................................................. 15
The Common Dialog Control ............................................................................................................................ 15
Standard Window Dialogs ................................................................................................................................ 16
Creating a new dialog box ................................................................................................................................ 20
Form load and unload ...................................................................................................................................... 20
Developing Code Modules ....................................................................................................................................... 25
Fundamental of Coding .................................................................................................................................... 25
Code Editor ...................................................................................................................................................... 26
Visual Basic Code Modules .............................................................................................................................. 26
Visual Basic Code Procedures .......................................................................................................................... 27
Defining Visual Basic Functions........................................................................................................................ 28
Code window tips and comments.................................................................................................................... 29
VB Statements and Comments ........................................................................................................................ 31
Manipulating Data ................................................................................................................................................... 33
Arithmetic expressions .................................................................................................................................... 33
VB Logical Operators ........................................................................................................................................ 34
VB Boolean Operators...................................................................................................................................... 34
Converting Variable Types ............................................................................................................................... 35
VB Array ........................................................................................................................................................... 35
Strings in Visual Basic ....................................................................................................................................... 37
Date Data Type................................................................................................................................................. 40
Writing Subroutines ................................................................................................................................................. 44
Application Structure ....................................................................................................................................... 44

ALL RIGHTS RESERVED TO SVTI 1


Purpose of Subroutines.................................................................................................................................... 44
Procedures ....................................................................................................................................................... 45
Functions .......................................................................................................................................................... 45
Arguments ........................................................................................................................................................ 46
ByRef vs. ByVal Parameters ............................................................................................................................. 47
Designing for Maintainability ........................................................................................................................... 48
Validating User Input ............................................................................................................................................... 49
Validating User Input ....................................................................................................................................... 49
Code ................................................................................................................................................................. 49
Visual Basic Validation ..................................................................................................................................... 50
Visual Basic Application Interfaces .......................................................................................................................... 52
Menus .............................................................................................................................................................. 52
Adding Icons to Menu Items ............................................................................................................................ 53
Toolbars............................................................................................................................................................ 55
The Status Bar control...................................................................................................................................... 56
Some Common Controls in VB.NET Control..................................................................................................... 57
VB.NET Arrays .................................................................................................................................................. 60
Database Client Applications ................................................................................................................................... 63
VB.Net - Database Access ................................................................................................................................ 63
ADO.Net Object Model .................................................................................................................................... 63
DataSet ............................................................................................................................................................. 64
Connecting to a Database ................................................................................................................................ 65
Creating Table, Columns and Rows.................................................................................................................. 71
Visual Basic Project Development Cycle .................................................................................................................. 73
Software Development life cycle – SDLC ......................................................................................................... 73
The Visual Basic Project Lifecycle ..................................................................................................................... 73
Create a project................................................................................................................................................ 74
Deploying VB Applications ............................................................................................................................... 77
Designing N-Tier Applications .......................................................................................................................... 80
Using Visual Basic Objects........................................................................................................................................ 81
Forms ............................................................................................................................................................... 81
Dialog Layout ........................................................................................................................................................... 84
Laying Out a Dialog Interface ........................................................................................................................... 84
Control indentation .......................................................................................................................................... 85
Working with Frames and Tab order. .............................................................................................................. 85
Dialog Hot/Shortkeys ....................................................................................................................................... 86
Dialog tools , techniques and validation control. ............................................................................................ 86
Data Declarations ..................................................................................................................................................... 88

ALL RIGHTS RESERVED TO SVTI 2


Scope in Visual Basic Programs ........................................................................................................................ 88
VB.NET Variable , Constant and Datatypes...................................................................................................... 89
VB.NET Variables Declaration .......................................................................................................................... 89
Logic and Iteration ................................................................................................................................................... 92
Logic Statements .............................................................................................................................................. 92
Conditional Constructs (If/Then, Select Case) ................................................................................................. 93
Iteration (Do Loop, For Loop)........................................................................................................................... 95
Loop Control Statements ................................................................................................................................. 95
Debugging and Error Handling ................................................................................................................................. 98
Types of Errors and Error Handling .................................................................................................................. 98
Debugging application ..................................................................................................................................... 98
Application Frameworks .......................................................................................................................................... 99
SDI and MDI Applications................................................................................................................................. 99
Display application lifecycle ............................................................................................................................. 99
I/O and Persistence .......................................................................................................................................... 99
Visual Basic File Access .................................................................................................................................... 99
File I/O Commands......................................................................................................................................... 100
File System Objects ........................................................................................................................................ 100
FSO Objects .................................................................................................................................................... 101
The Registry.................................................................................................................................................... 101
Deploying Applications .......................................................................................................................................... 102
The Packaging and Deployment Wizard ........................................................................................................ 102
Microsoft SQL Server 2016 .................................................................................................................................... 108
What is data? ................................................................................................................................................. 108
What is Information? ..................................................................................................................................... 108
Data vs Information ....................................................................................................................................... 108
What is Database? ......................................................................................................................................... 108
Database Management System ..................................................................................................................... 108
Database management system (dbms): ....................................................................................................... 108
Introduction to relational database ............................................................................................................... 108
How does a relational database work? .......................................................................................................... 109
What is the structure of a relational database model? ................................................................................. 109
Types of databases......................................................................................................................................... 110
What are the differences between relational databases, non-relational databases and NoSQL? ............... 112
Data Analysis .................................................................................................................................................. 114
Data Analysis Tools ........................................................................................................................................ 114
Database languages in SQL Server ................................................................................................................. 116
DML in SQL ..................................................................................................................................................... 118

ALL RIGHTS RESERVED TO SVTI 3


DCL in SQL ...................................................................................................................................................... 119
TCL in SQL ....................................................................................................................................................... 119
DATA MODELING ................................................................................................................................................... 120
Data modeling ................................................................................................................................................ 120
Types of data models ..................................................................................................................................... 120
Data modeling process................................................................................................................................... 122
Types of data modeling .................................................................................................................................. 122
Benefits of data modeling .............................................................................................................................. 123
Data modeling tools ....................................................................................................................................... 123
ANSI-SPARC Architecture ............................................................................................................................... 124
Three-level architecture................................................................................................................................. 124
Database schemas ......................................................................................................................................... 125
The Entity Relationship Data Model .............................................................................................................. 125
Normalization......................................................................................................................................................... 133
Normalization................................................................................................................................................. 133
Database Normal Forms ................................................................................................................................ 133
Denormalization in Databases ....................................................................................................................... 138
RELATIONSHIPS ...................................................................................................................................................... 139
Introduction to Database Relationships ........................................................................................................ 139
Types of Database Relationships ................................................................................................................... 139
Relationships and Referential Integrity ......................................................................................................... 140
SQL PERFORMANCE ............................................................................................................................................... 142
SQL - Indexes .................................................................................................................................................. 142
QUERY PERFORMANCE .................................................................................................................................. 143
Concurrency Control in SQL Server ................................................................................................................ 146
DATABASE OBJECTS ............................................................................................................................................... 149

ALL RIGHTS RESERVED TO SVTI 4


CHAPTER 01

INTRODUCTION TO VISUAL BASIC


Capabilities of Visual Basic
Visual Basic was developed by Microsoft to extend the capabilities of BASIC by adding objects and
“event-driven” programming: buttons, menus, and other elements of graphical user interfaces (GUIs).
Visual Basic can also be used within other Microsoft software to program small routines. Visual Basic
was succeeded in 2002 by Visual Basic .NET, a vastly different language based on C#, a language with
similarities to C++.

Visual Basic Overview


Visual Basic (VB) is a programming language developed by Microsoft in 1992. The purpose of this
language is to develop an application that can run on different versions of the Windows operating system.
A Visual Basic evolved from Basic Language; Basic language is easier to read than other languages. The
final version of Visual Basic was released in 1998. Microsoft then launched a Visual Basic DotNet
('VB.NET') language, which is much better than Visual Basic in all aspects such as performance,
reliability, working environment, easy to build, and debugging an application.
Features of Visual Basic
o User Interface design
o Rapid Application Development
o Using this language, you can use internet or intranet services in your application.

It has powerful database access tools, by which you can easily develop front end applications.
o It also supports ActiveX technology, in which you can access the features of other application in
system application. For example: Microsoft Word, Microsoft Excel, etc.

Types of Visual Basic Projects


Visual Studio 2010 comes with many project templates to create the necessary boilerplate code and files
you need to start developing applications. In the following table, you’ll find some definitions of project
types to help you decide which is the right project template for your needs.

Project Type Description


Class library Component library with no user interface
Console application Command line application
Database project SQL script storage
Device application Windows application for a smart device
Empty project Blank project
SQL Server project Management of stored procedures and SQL Server objects
Web service ASP.NET Web application with no user interface; technically, no
longer a project type
Web site ASP.NET Web application; technically, no longer a project
type
Windows Windows application with a user interface application
Windows service Windows application with no user interface
WPF Browser Windows Presentation Foundation browser application
Application

ALL RIGHTS RESERVED TO SVTI 5


Rapid Application Development
A programming system that enables programmers to quickly build working programs. In general, RAD
systems provide a number of tools to help build graphical user interfaces that would normally take a large
development effort. Two of the most popular RAD systems for Windows are Visual Basic and Delphi.
Microsoft Visual Basic has been used as the ultimate rapid application development tool for Windows
applications. The powerful Common Language Runtime and the vast .NET Framework class library
provide a consistent software platform for all .NET programming languages. Visual Basic now enjoys
virtually identical capabilities to other languages, including the new Visual C# and the ever-popular Visual
C++, while preserving the basic ease of use and strong RAD features that have made Visual Basic so
popular.

RAD Problems
Let us discuss the major problems with VB 6.0, which has been creating troubles for VB developers for a
long time.
 No capabilities for multithreading.
 Lack of implementation inheritance and other object oriented features.
 Poor error handling capabilities.
 Poor integration with other languages such as C++.
 No effective user interface for Internet based applications.

Visual Basic Editions


When we install Visual Basic IDE we have following basic 3 editions which are described below:

Select one to download IDE


o Visual Studio 2019 Community Edition
o Visual Studio 2019 Professional Edition (90 Day Free Trial)
o And Visual Studio 2019 Enterprise Edition (90 Day Free Trial)

ALL RIGHTS RESERVED TO SVTI 6


Step 1. For downloading the Visual Studio IDE, go through the link given below:

https://www.visualstudio.com/downloads

Select one to download IDE


o Visual Studio 2019 Community Edition
o Visual Studio 2019 Professional Edition (90 Day Free Trial)
o And Visual Studio 2019 Enterprise Edition (90 Day Free Trial)

The Visual Basic IDE


In this tutorial, we will use Visual Studio 2019 Professional Edition

Step 2. As clicked on download link, it starts downloading an .exe file, as shown in the image below.

Step 3. Click on the .exe file and then, it shows a pop-up window.

ALL RIGHTS RESERVED TO SVTI 7


Step 4. Click on the Run button, and then it shows the below image.

Step 5. Click on the Continue Button

Step 6. After clicking on Continue, Visual Studio will start downloading its initial files as shown in the
image below.

ALL RIGHTS RESERVED TO SVTI 8


Step 7. It shows the screen below, in which you have to click on the install button as shown.

Step 8. After clicking on install button, your Visual Studio IDE will start downloading and then it displays
the screen, as we have shown below.

Step 9. From the above image, select .NET desktop development and click on install open which may
take some time to download the Visual Studio in your system, as shown in below image.

ALL RIGHTS RESERVED TO SVTI 9


Step 10. After successfully downloading and installing the Visual Studio' supportive file, it shows the
below screen in your system.

Step 11. Click on Launch button, and then it shows the below image in your screen that represents Visual
Studio has been successfully launched in your machine.

And then it shows a below screen to select the Visual Studio theme. By default, it takes Blue theme, and
if you want to change, you can easily change the Visual Studio theme by clicking on other themes.

ALL RIGHTS RESERVED TO SVTI 10


Step 12. After selecting the Theme, click on Start Visual Studio and then it shows a below image in your
system screen for creating a new project.

Step 13. After click on Create a new project, it shows the below screen to choose what type of
application you are going to build in Visual studio. In this you can select the Console based application or
Window Form Based application, as shown in below image. Here we chose the Console based application,
and then click on the Next button.

Step 14. When you click the Next button, it shows the below image to define the project name, and also
reminds if you want to place the solution and project in the same directory.

ALL RIGHTS RESERVED TO SVTI 11


Step 15. And finally, your new project will be successfully created.

Managing the Workspace


The Visual Studio integrated development environment is a creative launching pad that you can use to
edit, debug, and build code, and then publish an app. An integrated development environment (IDE) is a
feature-rich program that can be used for many aspects of software development. Over and above the
standard editor and debugger that most IDEs provide, Visual Studio includes compilers, code completion
tools, graphical designers, and many more features to ease the software development process.

This image shows Visual Studio with an open project and several key tool windows you'll likely use:
 Solution Explorer (top right) lets you view, navigate, and manage your code files. Solution Ex-
plorer can help organize your code by grouping the files into solutions and projects.
 The editor window (center), where you'll likely spend a majority of your time, displays file contents.
This is where you can edit code or design a user interface such as a window with buttons and text
boxes.
 The Output window (bottom center) is where Visual Studio sends notifications such as debugging and
error messages, compiler warnings, publishing status messages, and more. Each message source has
its own tab.
 Team Explorer (bottom right) lets you track work items and share code with others using version
control technologies such as Git and Team Foundation Version Control (TFVC).

ALL RIGHTS RESERVED TO SVTI 12


CHAPTER 02

VB REFERENCE RESOURCES
Using the Integrated Documentation
This section provides reference information for various aspects of the Visual Basic language.
1. Typographic and Code Conventions.
Summarizes the way that keywords, placeholders, and other elements of the language are formatted in the
Visual Basic documentation.

2. Visual Basic Runtime Library Members


Lists the classes and modules of the Microsoft Visual Basic namespace, with links to their member
functions, methods, properties, constants, and enumerations.

3. Keywords
Lists all Visual Basic keywords and provides links to more information.

4. Attributes (Visual Basic)


Documents the attributes available in Visual Basic.

5. Constants and Enumerations


Documents the constants and enumerations available in Visual Basic.

6. Data Types
Documents the data types available in Visual Basic.

7. Directives
Documents the compiler directives available in Visual Basic.

8. Functions
Documents the run-time functions available in Visual Basic.

9. Modifiers
Lists the Visual Basic run-time modifiers and provides links to more information.

10. Modules
Documents the modules available in Visual Basic and their members.

11. Nothing
Describes the default value of any data type.

12. Objects
Documents the objects available in Visual Basic and their members.

13. Operators
Documents the operators available in Visual Basic.

14. Properties
Documents the properties available in Visual Basic.

ALL RIGHTS RESERVED TO SVTI 13


15. Queries
Provides reference information about using Language-Integrated Query (LINQ) expressions in
your code.

16. Statements
Documents the declaration and executable statements available in Visual Basic.

17. XML Comment Tags


Describes the documentation comments for which IntelliSense is provided in the Visual Basic Code
Editor.

18. XML Axis Properties


Provides links to information about using XML axis properties to access XML directly in your code.

19. XML Literals


Provides links to information about using XML literals to incorporate XML directly in your code.

20. Error Messages


Provides a listing of Visual Basic compiler and run-time error messages and help on how to handle them.

Microsoft Developer Network


Microsoft Developer Network (MSDN) was the division of Microsoft responsible for managing the firm's
relationship with developers and testers, such as hardware developers interested in the operating
system (OS), and software developers developing on the various OS platforms or using the API or
scripting languages of Microsoft's applications. The relationship management is situated in assorted
media: web sites, newsletters, developer conferences, trade media, blogs and DVD distribution. MSDN
now called Visual Studio Subscriptions, is one of Microsoft's most misunderstood products. The Visual
Studio Subscription (formerly MSDN) is one of the largest community platforms for developers working
on Microsoft technologies.

MSDN is a Microsoft program that provides developers with tools, information, training, and events to
help them develop products for Microsoft Windows platforms. MSDN Online, the Web site for developers
of Windows-based software, regularly features news, general information, and in-depth technical articles
and interviews.

ALL RIGHTS RESERVED TO SVTI 14


CHAPTER 03

DEVELOPING DATA ENTRY DIALOGS

Dialogs
A dialog box is a secondary window that allows users to perform a command, asks users a question, or
provides users with information or progress feedback.

A typical dialog box.


Dialog boxes consist of a title bar (to identify the command, feature, or program where a dialog box came
from), an optional main instruction (to explain the user's objective with the dialog box), various controls
in the content area (to present options), and commit buttons (to indicate how the user wants to commit to
the task).

Dialog boxes have two fundamental types:

 Modal dialog boxes require users to complete and close before continuing with the owner window.
These dialog boxes are best used for critical or infrequent, one-off tasks that require completion before
continuing.
 Modeless dialog boxes allow users to switch between the dialog box and the owner window as de-
sired. These dialog boxes are best used for frequent, repetitive, on-going tasks.

A task dialog is a dialog box implemented using the task dialog application programming interface
(API). They consist of the following parts, which can be assembled in a variety of combinations:

 A title bar to identify the application or system feature where the dialog box came from.
 A main instruction, with an optional icon, to identify the user's objective with the dialog.
 A content area for descriptive information and controls.
 A command area for commit buttons, including a Cancel button, and optional More options and Don't
show this again controls.
 A footnote area for optional additional explanations and help, typically targeted at less experienced
users.

The Common Dialog Control


The Common Dialog control provides a standard set of dialog boxes for operations such as opening,
saving, and printing files, as well as selecting colors and fonts and displaying help. Any six of the different
dialog boxes can be displayed with just one Common Dialog control. A particular dialog box is displayed
by using one of the six "Show..." methods of the Common Dialog
control: ShowOpen, ShowSave, ShowPrinter, ShowColor, ShowFont, or ShowHelp.

The Common Dialog control not an intrinsic control; rather, it is an "Active X" control that must be added
to the toolbox via the Components dialog box, as shown below. This dialog box is accessed via
the Project menu, Components item. Once you check "Microsoft Common Dialog Control 6.0" and
click OK, the control is added to your toolbox (also shown below, circled). Then you can double-click it
to make it appear on your form, as you would with any other control. The Common Dialog control is not
visible at run-time.

ALL RIGHTS RESERVED TO SVTI 15


The Components Dialog Box Common Dialog
Control Added to
Toolbox

Standard Window Dialogs


Dialog boxes are one means of requesting users for specific kinds of inputs. Therefore, VB.NET allows
its designers to create a number of different types of dialog boxes. Standard Dialog boxes are included in
classes that fall within the purview of the Common Dialog.
1. FileDialog
2. ColorDialog
3. FontDialog
4. PageSetupDialot
5. PrintDialog

Open File Dialog Class


This class provides users with the file selection capability. The properties and methods of this dialog boxes
are given below:

Property or Method Description


ShowDialog Displays the dialog
MultiSelect Sets/unsets the selection of multiple files
ShowReadOnly Sets/unsets the read-only check box checked
Filter Sets the type of files that will appear in the dialog box
FilterIndex Sets the index of the filter selected in the dialog box

ALL RIGHTS RESERVED TO SVTI 16


Save File Dialog Class
The SaveFileDialog class offers you the standard window that we see while saving the file. The methods
and properties of this dialog box are given below:

Property or Method Description


ShowDialog Displays the message
CheckFileExists Checks for the existence of file specified
FileName Determines the file name selected by the user
Filter Condition for files to be shown in the dialog box
FilterIndex Determine the index of the filter selected in the dialog box

The Color Dialog Class


This dialog box shows the color palette for allowing user to select a color and add that color to the palette.
The properties of the Class are given below:

Property or Method Description


ShowDialog Displays the dialog box
Color Determines the color selected by the user
AllowFullOpen Specifies if the user can add custom colors to the box
SolidColorOnly Determines if the user can use dithered colors

The following screenshot shows the usage of the color palette:


Create a new Visual Basic Windows Applications project in the Visual Studio IDE . To the form Form1
add a ColorDialogBox. Add two Buttons and name them as given below:

ALL RIGHTS RESERVED TO SVTI 17


Now in the code behind form add the following codes:

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click

Me.ColorDialog1.ShowDialog()

Label1.ForeColor = Me.ColorDialog1.Color

End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button2.Click

Me.Close()

End Sub
End Class
Press F5 to execute the program

The three screenshots below illustrate how different common dialog boxes are displayed..

“Change Color” button opens the ColorDialog box. You can choose any color from the palette and click
Ok. (The codes for event handling of Ok and Cancel button in the ColorDialogBox are not given in this
program. You may however write it as shown earlier, if you want to see the impact of your program.) The
next screenshot will show the changed fore color of the label1:

Creating a Custom Dialog Box


 In a new project which already has a form Form1, add another form and name it as FixeDialog.
 Set the Text property of this form as “Add Text”.
 Add a label control, a text box control and two command buttons.
 Change the text property of the label to “Enter Your Text!” and name the first button OK and the other
as Cancel.
 In the property sheet of the form set the FormBorderStyle property to FixedDialog
 Set the ControlBox property as false. This is done to remove minimize, maximize and close buttons.
 Enter the following codes for the Dialog Form:

Now press F5 to execute the program. The Following sequence of three screenshot will illustrate the
working of the form:

ALL RIGHTS RESERVED TO SVTI 18


The first screenshot shows the initial screen of the program:

The following screenshot shows the custom dialog box opened with the new text typed in the text box:

The final screenshot shows the changed label text as shown below:

ALL RIGHTS RESERVED TO SVTI 19


Creating a new dialog box
Let's create a simple program to display the dialog box in the VB.NET Windows Forms.

Dialog.vb

1. Public Class Dialog


2. Private Sub Dialog_Load(sender As Object, e As EventArgs) Handles MyBase.Load
3. Button1.Text = "Click Me" 'Set the name of button
4. Me.Text = "javatpoint.com" ' Set the title name for the Windows Form
5. Button1.BackColor = Color.Green ' Background color of the button
6. End Sub
7. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
8. Dim result1 As DialogResult = MessageBox.Show("Is VB.NET program-
ming laguage easy to learn?",
9. "Important Question",
10. MessageBoxButtons.YesNo)
11. End Sub
12. End Class
Output:

Now, click on the Click Me button of the Windows Form, it displays the dialog box, as shown below.

Form load and unload


Load and Unload are used to control the memory status of a form. These two statements always appear
before the name of the object to be affected. They are often confused with the Show and Hide methods
that take place after the object name. Show and Hide are used to control whether a form is visible to the
user.
Use the Load statement to load a form into memory without making it visible yet. The Load statement
will take only one argument: the name of the object to be loaded. Take a look at the following code:

Load Form1

Load frmTest

ALL RIGHTS RESERVED TO SVTI 20


When an individual form is no longer required, you can unload it from memory. This will release the
graphic components from memory.

The following code unloads two forms:

Unload Form1

Unload frmTest

VB.NET Form Controls


A Form is used in VB.NET to create a form-based or window-based application. Using the form, we can
build a attractive user interface. It is like a container for holding different control that allows the user to
interact with an application. The controls are an object in a form such as buttons,
Textboxes, Textarea, labels, etc. to perform some action. However, we can add any control to the runtime
by creating an instance of it.
A Form uses a System.Windows.Form namespace, and it has a wide family of controls that add both
forms and functions in a Window-based user interface.
1VB.NET Form Properties

The following are the most important list of properties related to a form. And these properties can be set
or read while the application is being executed.

Properties Description
BackColor It is used to set the background color for the form.
BackgroundImage It is used to set the background image of the form.
Cursor It is used to set the cursor image when it hovers over the form.
AllowDrop Using the AllowDrop control in a form, it allows whether to drag and drop on
the form.
Font It is used to get or set the font used in a form.
Locked It determines whether the form is locked or not.
FormBorderStyle It is used to set or get border style in a form.
Text It is used to set the title for a form window.
MinimizeBox MinimizeBox It is used to display the minimum option on the title bar of the
form.
IsMDIChild It is used to authenticate whether a form is a container of a Multiple Document
Interface (MDI) child form.
Autoscroll It allows whether to enable auto-scrolling in a form.
MaximizeBox It is used to display the maximum option on the title bar of the form.
MaximumSize It is used to set the maximum height and width of the form.
Language It is used to specifies the localized language in a form.
AcceptButton It is used to set the form button if the enter key is pressed.
Top, Left It is used to set the top-left corner coordinates of the form in pixel.
Name It is used to define the name of the form.
MinimumSize It is used to set the minimum height and width of the form.
Enabled It uses the True or False value to enable mouse or keyboard events in the form.
TopMost It uses a Boolean value that represents whether you want to put the window form
on top of the other form. By default, it is False.

ALL RIGHTS RESERVED TO SVTI 21


Form Events
Difference between JDK, JRE, and JVM
The following are the most important list of events related to a form.
Events Description
Activated An activated event is found when the user or program activates the form.
Click A click event is active when the form is clicked.
Closed A closed event is found before closing the form.
Closing It exists when a form is closing.
DoubleClick DoubleClick
The DoubleClick event is activated when a user double clicks on the form.
DragDrop A DragDrop event is activated when a drag and drop operation is performed.
MouseDown A MouseDown event is activated when the mouse pointer is on the form,
and the mouse button is pressed.
GotFocus A GotFocus event is activated when the form control receives a focus.
HelpButtonClicked It is activated when a user clicked on the help button.
KeyDown A KeyDown event is activated when a key is pressed while focussing on the
form.
KeyUp A KeyUp event is activated when a key is released while focusing on the
form.
Load The load event is used to load a form before it is first displayed.
LostFocus It is activated when the form loses focus.
MouseEnter A MouseEnter event is activated when the mouse pointer enters the form.
MouseHover A MouseHover event is activated when the mouse pointer put on the form.
MouseLeave A MouseLeave event is activated when the mouse pointer leaves the form
surface.
Shown It is activated whenever the form is displayed for the first time.
Scroll A Scroll event is activated when a form is scrolled through a user or code.
Resize A Resize event is activated when a form is resized.
Move A Move event is activated when a form is moved.

For creating a Windows Forms application in VB.NET, we need to follow the following steps in
Microsoft Visual Studio.
1. GoTo File Menu.
2. Click on New Project.
3. Click on Windows Forms App or Application

And finally, click on the 'Create' button to create your project, and then, it displays the following window
form with a name Form1.

ALL RIGHTS RESERVED TO SVTI 22


Now create a simple program of Windows form control in VB.NET.
Form1.vb
1. Public Class Form1
2. ' Create nameStr and num variables
3. Dim nameStr As String
4. Dim num As Integer
5. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
6. End Sub
7. ' It is Label1
8. Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
9. End Sub
10. It is TextBox1 for inserting the value.
11. Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.Tex
tChanged
12. End Sub
13. ' It is Label2
14. Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
15. End Sub
16. ' It is a Button1 for transferring the control.
17. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
18. nameStr = TextBox1.Text
19. num = TextBox2.Text
20. Label3.Text = "You have entered the Name " & nameStr + " Number " & num
21. End Sub
22. ' It is TextBox2 for inserting the value.
23. Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.Tex
tChanged
24. End Sub
25. ' It is label3
26. Private Sub Label3_Click(sender As Object, e As EventArgs) Handles Label3.Click
27. End Sub
28. End Class

ALL RIGHTS RESERVED TO SVTI 23


Output:

Now enter the following details in the form:

After filling all the details, click on the Submit button. After that, it shows the following Output:

ALL RIGHTS RESERVED TO SVTI 24


CHAPTER 04

DEVELOPING CODE MODULES


Fundamental of Coding
Here are five of the most important coding concepts that every young learner should know:
1. Variables
As the foundation of any computer programming language, variables act as “containers” that “hold”
information. These containers then store this information for later use.
For example, imagine you are visiting the homepage of a website. Once you land on this page, a dialog
box pops into view with this simple greeting: “Hi! What’s your name?” This dialog box is a variable!
In this code, the programmer could name this variable “visitorName.” This means that when you type
your name into the form and hit submit, your information would be stored in the “visitorName”
variable. The programmer could then reference this variable at any time to access the information it
contains.

2. Data Structures
Data structures allow programmers to streamline data collection when a large amount of related
information is involved. Let’s go back to our “visitorName” variable from above, but imagine the
computer programmer needs to store and reference 10 different visitors’ names rather than just one.
Rather than creating 10 different variables for each new visitor — which would increase the sheer
amount of text in the program and make adding or removing new contacts difficult — the programmer
could simply use a data structure to contain all related variables. In this case, the data structure would
be a List.
With this List data structure, the programmer only needs to create one variable rather than 10, which
means the code would be much more flexible to change.

3. Control Structures
A control structure analyzes variables and selects a direction in which to go determined from the given
parameters. For example, when a computer program is running, the code is being read by the computer
line by line from top to bottom and (for the most part) left to right.
As the code is being read, the computer will reach a point where it needs to make a “decision” (based
on strict rules set by the computer programmer). At this point, the code could do things like jump to a
different part of the program, re-run a certain piece of code again, or simply skip a block of code
altogether.
Whatever parameters are set by the programmer will affect the code flow. Think of control
structures as the directions your program needs to allow it to make choices and execute commands
under different conditions.

4. Syntax
Just like in the English language, computer programming follows a syntax or a set of rules that define
particular layouts of letters and symbols. Proper syntax ensures the computer reads and interprets code
accurately. For example, let’s consider a simple email address and its required syntax.
Email addresses are understood by readers and computers immediately due to their format. Typically,
email addresses must consist of a string of letters and numbers, followed by the “@” symbol, and
finally a website domain (e.g., [email protected]). This structure is known as the
standard email syntax! It’s easy to imagine that if the email address were not syntactically correct
([email protected]_smith), computers would not be able to process it.
In a similar fashion, each computer programming language has its own syntax or appropriate order in
how code should be written for the program to understand what it is supposed to do.

ALL RIGHTS RESERVED TO SVTI 25


5. Tools
In the physical world, tools allow workers to perform tasks that would otherwise be extremely difficult
(think of how a hammer helps drive a nail into a piece of wood and what this job would be like without
tools). Similarly, a tool in computer programming is a piece of software that helps programmers write
code much faster.
For example, one of the most important tools for computer programmers is an Integrated Development
Environment (IDE). An IDE can check the syntax of code for errors, organize files, autocomplete
commonly used code, and help you easily navigate through your code. Tools are the final crucial
element to code, as they streamline processes and ensure accuracy.

Code Editor

Use the Code window to write, display, and edit Visual Basic code. You can open as many Code windows
as you have modules, so you can easily view the code in different forms or modules, and copy and paste
between them.
You can open a Code window from:
 The Project window, by selecting a form or module, and choosing the View Code button.
 A UserForm window, by double-clicking a control or form, choosing Code from the View menu, or
pressing F7.
You can drag selected text to:
 A different location in the current Code window.
 Another Code window.
 The Immediate and Watch windows.
 The Recycle Bin.

Visual Basic Code Modules


Visual Basic application source code is structured into module files with a .vb suffix. By default, Visual
Studio creates a separate module file for each form in an application containing the code to construct the
form. For example, the code to create a form called Form1 will be placed in a module file
named Form1.Designer.vb. Similarly, any code that has been defined by the developer to handle events
from controls in the form will be placed by Visual Studio into a module file called Form1.vb.
We now need to learn how to create a new module in a project to contain our own Visual Basic code.
Begin by creating a new Windows Application project in Visual Studio called vbModules. Add two
TextBox controls (named value1TextBox and value2TextBox) and a button (labeled Calculate) to the
Form so that appears as follows:
<google>ADSDAQBOX_FLOW</google>

ALL RIGHTS RESERVED TO SVTI 26


Once the new project has been opened and the first form is visible, select Add Module... from
the Project menu. The Add Item window will appear with the Module item pre-selected:

Name the new module Math.vb and click the Add button. The new module will be added to the project
and a new tab labeled Math.vb for accessing the module code appears in the design area:

Now that we have added a new module to our project the next step is to add Visual Basic code to that
module. Before we can do that, however, we need to learn about Visual Basic procedures.
Visual Basic Code Procedures
Visual Basic procedures provide a way to break up code into logical and re-usable sections that can be
called from other sections of Visual Basic code. For example, you might have a section of Visual Basic
code that calculates the interest due on a loan.
Visual Basic provides two types of procedures:
 functions - Functions are procedures which perform a task and return a value when completed.
 subroutines - Subroutines are procedures which perform a task but return no value when completed.

ALL RIGHTS RESERVED TO SVTI 27


It is especially useful to be able to return values from functions. For example, the function may need to
return the result of the task it performed (perhaps the result of a calculation). A function might also return
a True or False value to indicate when the task was performed successfully. The Visual Basic code which
called the function then acts based on the returned value.
In the case of both subroutines and functions, values (known as parameters) may optionally be passed into
the procedure.

Defining Visual Basic Subroutines


Subroutines are declared inside Visual Basic Modules. Our newly created module in Visual Studio
contains the following:

Module Math
End Module

We are now going to add a subroutine called DisplayResult to this module. The syntax for a Visual Basic
subroutine is as follows:
scope Sub subroutineName(parameters)
End Sub
The scope value is either Private or Public depending on whether the Subroutine is to be accessible from
Visual Basic code outside of the current module. Sub is the Visual Basic keyword which indicates this is
a Subroutine rather than a Function. subroutineName is the name of the Subroutine and is used when this
specific procedure is to be called.
We can write code in the Subroutine to display a message window as follows:

Module Math
Public Sub DisplayResult()
MessageBox.Show("Test message")
End Sub
End Module

Next, the Click event procedure of the button in our form needs to call the DisplayResult() Subroutine.
Double click on the button in the form to display the event procedure code and add the call
to DisplayResult() as follows:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
DisplayResult()
End Sub

Defining Visual Basic Functions


Visual Basic Functions differ from Subroutines in that they return a value. The syntax for declaring a
Function is as follows:

scope Function functionName(parameters) As datatype

ALL RIGHTS RESERVED TO SVTI 28


With this syntax in mind we can create a Function for our application that will accept the values from our
two text fields as parameters, perform the calculation and return the result as an Integer:

Public Function PercentageOf(ByVal value1 As Integer, ByVal value2 As Integer) As Integer


Dim result As Integer
result = (value1 / value2) * 100
Return result
End Function

The final step, is to modify our Button control Click event procedure to call the PercentageOf() function,
passing through the Text properties of our two TextBox controls. The result returned by this function is
then passed to the DisplayResult() Subroutine where it is displayed in a message window:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
DisplayResult(PercentageOf(value1TextBox.Text, value2TextBox.Text))
End Sub

After making the above change, press F5 to build and run the application.
Code window tips and comments
Applying block comments
Placing a single apostrophe in front of any line of code tells Excel to skip that line of code. This technique
is called commenting out code. Most programmers use the single apostrophe to create comments or notes
in the code, as shown here.

A single apostrophe in front of any line turns that line into a comment.
It’s sometimes beneficial to comment out multiple lines of code. This way, you can test certain lines of
code while telling Excel to ignore the commented lines.

ALL RIGHTS RESERVED TO SVTI 29


Instead of spending time commenting out one line at a time, you can use the Edit toolbar to comment out
an entire block of code. To activate the Edit toolbar, go to the VBE menu and choose
View→Toolbars→Edit. Select the lines of code you want commented out and then click the Comment
Block icon on the Edit toolbar, as shown here.

Use the Edit toolbar to apply comments to a block of code.

Copying multiple lines of code

You can copy entire blocks of code by highlighting the lines you need, and then holding down the Ctrl
key while dragging the block. This old Windows trick works even when you drag across modules.

You’ll know that you are dragging a copy when your cursor shows a plus symbol next to it, as shown
here.

Ctrl-drag to create a copy.


Jumping between modules and procedures
After your cache of macro code starts to grow, it can be a pain to quickly move between modules and
procedures. You can ease the pain by using a few hot keys.
 Press Ctrl+Tab to quickly move between modules.
 Press Ctrl+Page Up and Ctrl+Page Down to move between procedures within a module.

Teleporting to your functions


When reviewing a macro, you may encounter a variable or a function name that is obviously pointing to
some other piece of code. Instead of scouring through all modules to find where that function or variable
name comes from, you can simply place your cursor on that function or variable name and press Shift+F2.
As this figure illustrates, you are instantly teleported to the origin of that function or variable name.
Pressing Ctrl+Shift+F2 will take you back to where you started.
ALL RIGHTS RESERVED TO SVTI 30
Press Shift+F2 on a function or variable name to be taken to it.
Staying in the right procedure
When your modules contain multiple procedures, scrolling through a particular procedure without
inadvertently scrolling into another procedure can be difficult. You will often find yourself scrolling up
and then down, trying to get back to the correct piece of code.
To avoid this nonsense, click the Procedure View button at the lower-left corner of VBE, as shown here.
Doing so limits scrolling to only the procedure you’re in.

VB Statements and Comments


A statement in Visual Basic is a complete instruction. It can contain keywords, operators, variables,
constants, and expressions. Each statement belongs to one of the following categories:
 Declaration Statements, which name a variable, constant, or procedure, and can also specify a data
type.
 Executable Statements, which initiate actions. These statements can call a method or function, and
they can loop or branch through blocks of code. Executable statements include Assignment State-
ments, which assign a value or expression to a variable or constant.

This topic describes each category. Also, this topic describes how to combine multiple statements on a
single line and how to continue a statement over multiple lines.

ALL RIGHTS RESERVED TO SVTI 31


Declaration statements
You use declaration statements to name and define procedures, variables, properties, arrays, and constants.
When you declare a programming element, you can also define its data type, access level, and scope. For
more information, see Declared Element Characteristics.
The following example contains three declarations.
VBCopy
Public Sub ApplyFormat()
Const limit As Integer = 33
Dim thisWidget As New widget
' Insert code to implement the procedure.
End Sub

Adding comments
Comment lines begin with an apostrophe (') or REM followed by a space. They can be added anywhere
in code, except within a string. To append a comment to a statement, insert an apostrophe or REM after
the statement, followed by the comment. Comments can also go on their own separate line. The following
example demonstrates these possibilities.

VBCopy
' This is a comment on a separate code line.
REM This is another comment on a separate code line.
x += a(i) * b(i) ' Add this amount to total.
MsgBox(statusMessage) REM Inform operator of status.

ALL RIGHTS RESERVED TO SVTI 32


CHAPTER 05

MANIPULATING DATA
Arithmetic expressions
Following table shows all the arithmetic operators supported by VB.Net. Assume variable A holds 2 and
variable B holds 7, then −
Operator Description Example
^ Raises one operand to the power of another B^A will give 49
+ Adds two operands A + B will give 9
- Subtracts second operand from the first A - B will give -5
* Multiplies both operands A * B will give 14
/ Divides one operand by another and returns a floating point result B / A will give 3.5
\ Divides one operand by another and returns an integer result B \ A will give 3
MOD Modulus Operator and remainder of after an integer division B MOD A will give 1

Example: Try the following example to understand all the arithmetic operators available in VB.Net −
Module operators
Sub Main()
Dim a As Integer = 21
Dim b As Integer = 10
Dim p As Integer = 2
Dim c As Integer
Dim d As Single

c=a+b
Console.WriteLine("Line 1 - Value of c is {0}", c)

c=a-b
Console.WriteLine("Line 2 - Value of c is {0}", c)

c=a*b
Console.WriteLine("Line 3 - Value of c is {0}", c)

d=a/b
Console.WriteLine("Line 4 - Value of d is {0}", d)

c=a\b
Console.WriteLine("Line 5 - Value of c is {0}", c)

c = a Mod b
Console.WriteLine("Line 6 - Value of c is {0}", c)

c=b^p
Console.WriteLine("Line 7 - Value of c is {0}", c)
Console.ReadLine()
End Sub End Module

ALL RIGHTS RESERVED TO SVTI 33


When the above code is compiled and executed, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of d is 2.1
Line 5 - Value of c is 2
Line 6 - Value of c is 1
Line 7 - Value of c is 100

VB Logical Operators
Following table shows all the logical operators supported by VB.Net. Assume variable A holds Boolean
value True and variable B holds Boolean value False, then −
Operator Description Example
And It is the logical as well as bitwise AND operator. If both the operands are (A And B) is
true, then condition becomes true. This operator does not perform short- False.
circuiting, i.e., it evaluates both the expressions.
Or It is the logical as well as bitwise OR operator. If any of the two operands (A Or B) is
is true, then condition becomes true. This operator does not perform short- True.
circuiting, i.e., it evaluates both the expressions.
Not It is the logical as well as bitwise NOT operator. Used to reverse the logical Not(A And
state of its operand. If a condition is true, then Logical NOT operator will B) is True.
make false.
Module logicalOp
Sub Main()
Dim a As Boolean = True
Dim b As Boolean = True
Dim c As Integer = 5
Dim d As Integer = 20
'logical And, Or and Xor Checking

If (a And b) Then
Console.WriteLine("Line 1 - Condition is true")
End If
If (a Or b) Then
Console.WriteLine("Line 2 - Condition is true")
End If
If (Not (a And b)) Then
Console.WriteLine("Line 10 - Condition is true")
End If

Console.ReadLine()
End Sub
End Module
VB Boolean Operators
A Boolean expression is an expression that evaluates to a value of the Boolean Data
Type: True or False. Boolean expressions can take several forms. The simplest is the direct comparison
of the value of a Boolean variable to a Boolean literal, as shown in the following example.

ALL RIGHTS RESERVED TO SVTI 34


VBCopy
If newCustomer = True Then
' Insert code to execute if newCustomer = True.
Else
' Insert code to execute if newCustomer = False.
End If

Converting Variable Types


In many situations, you will need to convert variables from one type into another. In addition to the
methods of the Convert class, you can still use the data-conversion functions of VB (CInt() to convert a
numeric value to an Integer, CDbl() to convert a numeric value to a Double, CSng() to convert a numeric
value to a Single, and so on), which you can look up in the documentation. If you’re writing new
applications in VB 2008, use the new Convert class to convert between data types.
To convert the variable initialized as the following

Dim A As Integer
Code language: VB.NET (vbnet)
to a Double, use the ToDouble method of the Convert class:

Dim B As Double
B = Convert.ToDouble(A)
Code language: VB.NET (vbnet)
Suppose that you have declared two integers, as follows:

Dim A As Integer, B As Integer


A = 23
B=7
Code language: VB.NET (vbnet)
The result of the operation A / B will be a Double value. The following statement

Debug.Write(A / B)
Code language: VB.NET (vbnet)
displays the value 3.28571428571429. The result is a Double value, which provides the greatest possible
accuracy.

Method Converts Its Argument To


ToBoolean Boolean
ToByte Byte
ToChar Unicode character
ToDateTime Date
ToDecimal Decimal
ToDouble Double

VB Array
An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection of variables of the same
type.

ALL RIGHTS RESERVED TO SVTI 35


All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.

Creating Arrays in VB.Net


To declare an array in VB.Net, you use the Dim statement. For example,
Dim intData(30) ' an array of 31 elements
Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _
"Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}
The elements in an array can be stored and accessed by using the index of the array. The following
program demonstrates this −
Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '

For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '

For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
ALL RIGHTS RESERVED TO SVTI 36
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110

Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular arrays.
You can declare a 2-dimensional array of strings as −
Dim twoDStringArray(10, 20) As String
or, a 3-dimensional array of Integer variables −
Dim threeDIntArray(10, 10, 10) As Integer
The following program demonstrates creating and using a 2-dimensional array −
Module arrayApl
Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '

For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8

Strings in Visual Basic


Strings are the most important data types in computer languages.

First example
A string literal is the notation for representing a string value within the text of a computer program. In
Visual Basic string literals are enclosed by double quotes. A string in Visual Basic is a sequence of
Unicode characters.
Option Strict On
Module Example
Sub Main()

ALL RIGHTS RESERVED TO SVTI 37


Dim str1 As String = "There are 10"
Dim str2 As String = " apples"

Console.WriteLine(str1 + str2)

Console.WriteLine("The length of the first string is " _


+ str1.Length.ToString() + " characters")

End Sub
End Module

In the preceding example, we create two string variables. Then we add them and compute the length of
the first string.
Dim str1 As String = "There are 10"
A string variable is declared and initiated.
Console.WriteLine(str1 + str2)
Two strings are concatenated. We use the + operator to add two strings.
Console.WriteLine("The length of the first string is " _
+ str1.Length.ToString() + " characters")
The Length property is used to determine the length of the string.
$ ./basics.exe
There are 10 apples
The length of the first string is 12 characters
Running the example gives this result.
Using quotes
Double quotes are used to create a string literal in Visual Basic. What if we wanted to display quotes, for
example in a direct speech? To print a double quote, it must be preceded by another double quote.
Option Strict On
Module Example
Sub Main()
Console.WriteLine("There are many stars.")
Console.WriteLine("He said, ""Which one is your favourite?""")
End Sub
End Module

When printing double quotes to the console, they must be preceded by another double quote.
Console.WriteLine("He said, ""Which one is your favourite?""")

Here we show, how to print a direct speech to the console. If we did not use two double quotes, the
compiler would be misled. It would see two consecutive strings.
$ ./quotes.exe
There are many stars.
He said, "Which one is your favourite?"
Output.
Multiline strings
It is possible to create a multiline string in Visual Basic.

ALL RIGHTS RESERVED TO SVTI 38


Option Strict On

Module Example
Sub Main()
Dim multiString As String = "I cheated myself" + vbNewLine + _
"like I knew I would" + vbNewLine + _
"I told ya, I was trouble" + vbNewLine + _
"you know that I'm no good"
Console.WriteLine(multiString)
End Sub
End Module

The example creates a string that spans several lines. We use a line continuation character, a plus operator
and a vbNewLine display constant.
$ ./multiline.exe
I cheated myself
like I knew I would
I told ya, I was trouble
you know that I'm no good
This text is displayed in four lines. All the text was assigned to one string variable.
Comparing strings
Option Strict On
Module Example
Sub Main()
Console.WriteLine("12" = "12") 'Returns True
Console.WriteLine("17" < "9") ' Returns True
Console.WriteLine("aa" > "ab") ' Returns False
End Sub
End Module

Comparison operators work differently in a string context.


Console.WriteLine("17" < "9") 'Returns True
Value 17 is not smaller than 9. But when applying < on two strings, we do not compare numbers. We
compare the sorting order of the characters. 1 is before 9 and is therefore has a 'lower position' and the
comparison returns True.

Console.WriteLine("aa" > "ab") ' Returns False


If the first two characters are equal, the operation continues on the following ones. The a character is
before the b, and the comparison operation returns False.
There is a String.Compare() method, which compares two specified strings and returns an integer that
indicates their relative position in the sort order. If the returned value is less than zero, the first string is
less than the second. If it returns zero, both strings are equal. Finally, if the returned value is greater than
zero, the first string is greater than the second.
Option Strict On
Module Example
Sub Main()
Dim str1 As String = "Visual Basic"
Dim str2 As String = "visual basic"

ALL RIGHTS RESERVED TO SVTI 39


Console.WriteLine(String.Compare(str1, str2, True))
Console.WriteLine(String.Compare(str1, str2, False))

End Sub
End Module

There is an optional third ignoreCase argument that determines if the case should be honoured.
Console.WriteLine(String.Compare(str1, str2, True))

Compare two strings and ignore the case. This line prints 0 to the console.
There is a Like operator, which can be used for simple regular expression matching.
Option Strict On
Module Example
Dim words() As String = {"Seven", "even", "Maven", "Amen", "Leven"}
Sub Main()
For Each word As String In words
If word Like "?*even" Then
Console.WriteLine("{0} matches the pattern", word)
Else
Console.WriteLine("{0} does not match the pattern", word)
End If
Next
End Sub
End Module

Date Data Type


Holds IEEE 64-bit (8-byte) values that represent dates ranging from January 1 of the year 0001 through
December 31 of the year 9999, and times from 12:00:00 AM (midnight) through 11:59:59.9999999 PM.
Each increment represents 100 nanoseconds of elapsed time since the beginning of January 1 of the year
1 in the Gregorian calendar. The maximum value represents 100 nanoseconds before the beginning of
January 1 of the year 10000.
Use the Date data type to contain date values, time values, or date and time values.
The default value of Date is 0:00:00 (midnight) on January 1, 0001.
You can get the current date and time from the DateAndTime class.

Workarounds
To convert a Date literal to the format of your locale, or to a custom format, supply the literal to
the Format function, specifying either a predefined or user-defined date format. The following example
demonstrates this.
MsgBox("The formatted date is " & Format(#5/31/1993#, "dddd, d MMM yyyy"))
Alternatively, you can use one of the overloaded constructors of the DateTime structure to assemble a
date and time value. The following example creates a value to represent May 31, 1993 at 12:14 in the
afternoon.
Dim dateInMay As New System.DateTime(1993, 5, 31, 12, 14, 0)

ALL RIGHTS RESERVED TO SVTI 40


Hour Format
You can specify the time value in either 12-hour or 24-hour format, for example #1:15:30
PM# or #13:15:30#. However, if you do not specify either the minutes or the seconds, you must specify
AM or PM.

Date and Time Defaults


If you do not include a date in a date/time literal, Visual Basic sets the date part of the value to January 1,
0001. If you do not include a time in a date/time literal, Visual Basic sets the time part of the value to the
start of the day, that is, midnight (0:00:00).

Currency data type


Currency variables are stored as 64-bit (8-byte) numbers in an integer format, scaled by 10,000 to give a
fixed-point number with 15 digits to the left of the decimal point and 4 digits to the right.
This representation provides a range of -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
The type-declaration character for Currency is the at (@) sign.
The Currency data type is useful for calculations involving money and for fixed-point calculations in
which accuracy is particularly important.

Variant data type


The Variant data type is the data type for all variables that are not explicitly declared as some other type
(using statements such as Dim, Private, Public, or Static).

The Variant data type has no type-declaration character.

A Variant is a special data type that can contain any kind of data except fixed-length String data.
(Variant types now support user-defined types.) A Variant can also contain the special
values Empty, Error, Nothing, and Null. You can determine how the data in a Variant is treated by using
the VarType function or TypeName function.

Use the VarType function to test what type of data is held in a Variant.

Numeric data can be any integer or real number value ranging from -1.797693134862315E308 to -
4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive
values.

The Variant data type is the data type for all variables that are not explicitly declared as some other type
(using statements such as Dim, Private, Public, or Static).

The Variant data type has no type-declaration character.

A Variant is a special data type that can contain any kind of data except fixed-length String data.
(Variant types now support user-defined types.) A Variant can also contain the special
values Empty, Error, Nothing, and Null. You can determine how the data in a Variant is treated by using
the VarType function or TypeName function.

Use the VarType function to test what type of data is held in a Variant.

Numeric data can be any integer or real number value ranging from -1.797693134862315E308 to -
4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive
values.

Format function for Numbers

ALL RIGHTS RESERVED TO SVTI 41


The Format function in Visual Basic 2017 is a very useful formatting function. It is used for formatting
output styles. It can also be used to display date and time in various formats. There are two types of Format
functions, the built-in Format function and the user-defined Format function
Built-in Format function for Numbers
The syntax of the built-in Format function is
Format (n, “style argument”)
where n is a number.
The list of style arguments in Visual Basic 2017 is given in Table 20.1.
Style Explanation Example
argument
General To display the number without having separators Format(8972.234, "General
Number between thousands. Number")=8972.234
Fixed To display the number without having separators Format(8972.2,
between thousands and rounds it up to two decimal "Fixed")=8972.23
places.
Standard To display the number with separators or separators Format(6648972.265,
between thousands and rounds it up to two decimal "Standard")= 6,648,972.27
places.
Currency To display the number with the dollar sign in front, has Format(6648972.265,
separators between thousands as well as rounding it up "Currency")= $6,648,972.27
to two decimal places.
Percent Converts the number to the percentage form and Format(0.56324,
displays a % sign and rounds it up to two decimal "Percent")=56.32 %
places.

Private Sub BtnFormat_Click(sender As Object, e As EventArgs) Handles BtnFormat.Click


Label1.Text = Format(8972.234, "General Number")
Label2.Text = Format(8972.2, "Fixed")
Label3.Text = Format(6648972.265, "Standard")
Label4.Text = Format(6648972.265, "Currency")
Label5.Text = Format(0.56324, "Percent")
End Sub
The Output

User-Defined Format
The syntax of the user-defined Format function is
Format (n, “user’s format”)
ALL RIGHTS RESERVED TO SVTI 42
Although it is known as user-defined format, we still need to follows certain formatting styles. Examples
of user-defined formatting style are listed in Table 19.2
Format Description Output
Format(781234.576,"0") Rounds to whole number without separators 781235
between thousands
Format(781234.576,"0.0") Rounds to 1 decimal place without separators 781234.6
between thousands
Format(781234.576,"0.00") Rounds to 2 decimal place without separators 781234.58
between thousands
Format(781234.576,"#,##0.00") Rounds to 2 decimal place with separators between 781,234.58
thousands
Format(781234.576,"$#,##0.00") Displays dollar sign and Rounds to 2 decimal place $781,234.58
with separators between thousands
Format(0.576,"0%") Converts to percentage form without decimal place 58%
Format(0.5768,"0%") Converts to percentage form with two decimal 57.68%
places

Private Sub BtnFormat_Click(sender As Object, e As EventArgs) Handles BtnFormat.Click


Label1.Text = Format(8972.234, "0.0")
Label2.Text = Format(8972.2345, "0.00")
Label3.Text = Format(6648972.265, "#,##0.00")
Label4.Text = Format(6648972.265, "$#,##0.00")
Label5.Text = Format(0.56324, "0%")
End Sub

The Output

ALL RIGHTS RESERVED TO SVTI 43


CHAPTER 06

WRITING SUBROUTINES
Application Structure
A Visual Basic program is built up from standard building blocks. A solution comprises one or more
projects. A project in turn can contain one or more assemblies. Each assembly is compiled from one or
more source files. A source file provides the definition and implementation of classes, structures, modules,
and interfaces, which ultimately contain all your code.

Purpose of Subroutines
Subroutines make programs shorter as well as easier to read and understand, because they break program
code into smaller sections. You can test procedures or functions separately, rather than having to test the
whole program. This makes programs easier to debug.
There are a number of advantages to using subroutines to create ‘out of line’ blocks of code that can be
called by other parts of the program:
 Subroutines make programs shorter as well as easier to read and understand, because they break
program code into smaller sections.
 You can test procedures or functions separately, rather than having to test the whole program. This
makes programs easier to debug.
 When creating very large programs, you can give different programmers different subroutines to
write, and these can then be combined.
 If something needs to be changed in a subroutine, it only needs to be changed once, within the
subroutine code. This change will then take effect wherever in the program the subroutine is used.
 You can use a subroutine many times in a program; if you wanted to repeat the same set of
instructions several times in a program without using a subroutine, you would have to write the
same code repeatedly.
 Data that is passed to a subroutine can be customised, so a subroutine can perform the same action
on different data.
 You can add subroutines to a library so that you can use them in other programs.

ALL RIGHTS RESERVED TO SVTI 44


Procedures
A procedure is a block of Visual Basic statements inside Sub, End Sub statements. Procedures do not
return values.
Option Strict On
Module Example
Sub Main()
SimpleProcedure()
End Sub
Sub SimpleProcedure()
Console.WriteLine("Simple procedure")
End Sub
End Module

This example shows basic usage of procedures. In our program, we have two procedures.
The Main() procedure and the user defined SimpleProcedure(). As we already know,
the Main() procedure is the entry point of a Visual Basic program.

SimpleProcedure()

Each procedure has a name. Inside the Main() procedure, we call our user
defined SimpleProcedure() procedure.
Sub SimpleProcedure()
Console.WriteLine("Simple procedure")
End Sub

Procedures are defined outside the Main() procedure. Procedure name follows the Sub statement. When
we call a procedure inside the Visual Basic program, the control is given to that procedure. Statements
inside the block of the procedure are executed.
Functions
A function is a block of Visual Basic statements inside Function, End Function statements. Functions
return values.
There are two basic types of functions. Built-in functions and user defined ones. The built-in functions are
part of the Visual Basic language. There are various mathematical, string or conversion functions.
Option Strict On
Module Example
Sub Main()
Console.WriteLine(Math.Abs(-23))
Console.WriteLine(Math.Round(34.56))
Console.WriteLine("ZetCode has {0} characters", _
Len("ZetCode"))
End Sub
End Module

In the preceding example, we use two math functions and one string function. Built-in functions help
programmers do some common tasks.
In the following example, we have a user defined function.
Option Strict On

ALL RIGHTS RESERVED TO SVTI 45


Module Example
Dim x As Integer = 55
Dim y As Integer = 32
Dim result As Integer
Sub Main()
result = Addition(x, y)
Console.WriteLine(Addition(x, y))
End Sub
Function Addition(ByVal k As Integer, _
ByVal l As Integer) As Integer
Return k+l
End Function
End Module

Two values are passed to the function. We add these two values and return the result to
the Main() function.
result = Addition(x, y)

Addition function is called. The function returns a result and this result is assigned to the result variable.
Function Addition(ByVal k As Integer, _
ByVal l As Integer) As Integer
Return k+l
End Function

This is the Addition function signature and its body. It also includes a return data type, for the returned
value. In our case is is an Integer. Values are returned to the caller with the Return keyword.
Arguments
When you call a Sub or Function procedure, you can supply arguments positionally, in the order that they
appear in the procedure's definition, or you can supply the arguments by name without regard to position.
For example, the following Sub procedure takes three arguments.

PassArgs(strName As String, intAge As Integer, dteBirth As Date)


Sub
Debug.Print strName, intAge, dteBirth
End Sub

You can call this procedure by supplying its arguments in the correct position, each delimited by a comma,
as shown in the following example.
PassArgs "Mary", 29, #2-21-69#
You can also call this procedure by supplying named arguments, delimiting each with a comma.
PassArgs intAge:=29, dteBirth:=#2/21/69#, strName:="Mary"

A named argument consists of an argument name followed by a colon and an equal sign (:=), followed by
the argument value.
Named arguments are especially useful when you are calling a procedure that has optional arguments. If
you use named arguments, you don't have to include commas to denote missing positional arguments.
Using named arguments makes it easier to keep track of which arguments you passed and which you
omitted.

ALL RIGHTS RESERVED TO SVTI 46


Optional arguments are preceded by the Optional keyword in the procedure definition. You can also
specify a default value for the optional argument in the procedure definition. For example:
Sub OptionalArgs(strState As String, Optional strCountry As String = "USA")
...
End Sub

When you call a procedure with an optional argument, you can choose whether or not to specify the
optional argument. If you don't specify the optional argument, the default value, if any, is used. If no
default value is specified, the argument would be for any variable of the specified type.
The following procedure includes two optional arguments, the varRegion and varCountry variables.
The IsMissing function determines whether an optional Variant argument has been passed to the
procedure.

Sub OptionalArgs(strState As String, Optional varRegion As Variant, _


Optional varCountry As Variant = "USA")
If IsMissing(varRegion) And IsMissing(varCountry) Then
Debug.Print strState
ElseIf IsMissing(varCountry) Then
Debug.Print strState, varRegion
ElseIf IsMissing(varRegion) Then
Debug.Print strState, varCountry
Else
Debug.Print strState, varRegion, varCountry
End If
End Sub

You can call this procedure by using named arguments as shown in the following example.
OptionalArgs varCountry:="USA", strState:="MD"
OptionalArgs strState:= "MD", varRegion:=5

ByRef vs. ByVal Parameters


ByVal in VB.NET means that a copy of the provided value will be sent to the function. For value types
(Integer, Single, etc.) this will provide a shallow copy of the value. With larger types this can be
inefficient. For reference types though (String, class instances) a copy of the reference is passed. Because
a copy is passed in mutations to the parameter via = it won't be visible to the calling function.

ByRef in VB.NET means that a reference to the original value will be sent to the function (1). It's almost
like the original value is being directly used within the function. Operations like = will affect the original
value and be immediately visible in the calling function.

ALL RIGHTS RESERVED TO SVTI 47


Designing for Maintainability
Best way to design my UI for In order to increase availability and minimize the cost of maintenance, we
have to deliberately design the system to accommodate the needs of maintenance.Here are 8 factors to
consider when designing a system that will require maintenance.
1. Standardization
Select from the smallest set of parts (one screw instead of 10 different types of screws) with as much
compatibility as possible. Minimize spare parts inventory is just one benefit.
Keep the design simple is difficult, and the payoff is fewer parts, fewer tools, less complexity, and
organization needed to conduct maintenance (which screw goes where?).
2. Modularization
Create a set of standard sizes, shapes, modular units. Lego bricks come to mind.
If we expect to different models with different features, using a standard structure allows the
interchange of compatible parts to alter functionally without changing the majority of the product. A
good example is light bulbs. You can select the functional bulbs (brightness, intensity, color, etc.) and
they will fit in the same socket.
3. Functional packaging
Gather all the required elements to complete a maintenance task in one kit. If I need washers, o-rings,
and pumper’s grease to complete a faucet repair, having all the items in one package helps me complete
the task quickly (without the need to run to the store to pick up the forgotten item.)
4. Interchangeability
If you have to create a custom fit for a part, consider the ramifications. Single source, lack of
compatibility with other similar functioning parts, another spare part in inventory, and limitations on
future design changes if you want to stay in that custom form factor.
Select parts that are useful for a range of products or applications. Manage and control the dimensional
and functional design tolerances.
5. Accessibility
Bruised knuckles are one risk of getting this wrong.
If an item requires replacement or adjustment as part of the expected maintenance, then it should
permit access. Consider tools, lighting, environment, and experience of a maintenance crew. Providing
access panels is one factor, safety another.
6. Malfunction annunciation
A key step in performing maintenance is to know what caused the problem or which parts are damaged
and require replacement.
A bicycle flat tire is obvious to visual inspection or you may notice a change in the sound and feel of
the ride. On complex systems which circuit board requires replacement may not be obvious.
Minimizing the need for inspection tools and diagnostic tasks minimizes the time/cost of the corrective
maintenance tasks. Let the system inform the technician what requires attention.
7. Fault isolation
There are two parts to this factor. One, make the system as informative as possible such that it not only
signals a failure mode, it also narrows down the possible failure mechanisms. Replacing a blown fuse
doesn’t fix the problem and just finding the problem may take significant time.
Second, a failure in one part of a system can cause failure of other elements in the system.
When possible, contain the damage to minimize the amount of damage caused by a failure of one item.
8. Identification
Name the parts with unique identifiers. This streamlines documentation, procedures, and maintenance
tasks.
Be consistent and provide meaningful or memorable naming conventions to avoid confusion.

ALL RIGHTS RESERVED TO SVTI 48


CHAPTER 07

VALIDATING USER INPUT


Validating User Input
In simple terms, validation refers to ensuring entered data is well, valid. Determining whether or not data
is valid can sometimes be a painstaking process as there are numerous tests that need to be thought of.
These tests include:
 Format test - This test determines if the entered string is in the correct format.
 Type test - This test checks if the input is the correct type. For example: Integers of dates that do not
need conversion afterwards.
 Permitted Character test - This test ensure that no illegal characters are entered. For example: If a
user is supposed to enter a name, numbers and some special symbols must not be allowed.
 Range test - This tests checks to see if entered values are within a specified range. For example : If
you are only supposed to type in 50 characters, you must not be able to enter more than fifty.

There are some more tests, but I want to keep this article straightforward and basic enough.

An Example Project
Because it is always easy to learn by doing things practically, you will be creating an app that makes use
of Regular Expressions to determine valid input.
Start Visual Studio and create a Desktop VB.NET application and design the form to resemble Figure.

Code
The Regular Expression's functionalities exist in the System.Text.RegularExpressions namespace, so let
us add that first:
Imports System.Text.RegularExpressions ' Regular Expressions Namespace
Add the following four variables inside the General Declarations section:
Private NameValid As Boolean 'Is Name Valid?
Private SurnameValid As Boolean 'Is Surname Valid?
Private PhoneValid As Boolean 'Is Phone Number Valid?
Private EmailValid As Boolean 'Is Email Valid?

These objects will determine if all our data is valid or not. Based on each of these variables' values, we
will know if the data is correct or not.

ALL RIGHTS RESERVED TO SVTI 49


Visual Basic Validation
Step 1: Create a Windows form application.

Step 2: Choose “ErrorProvider” form toolbox.

Step 3: Select the Text box and go to its properties.

ALL RIGHTS RESERVED TO SVTI 50


In properties choose “Events” and under focus double click on “validating”.
Now we have the text box validation method.

1. private void textBoxName_Validating(object sender, CancelEventArgs e)


2. {
3. if (string.IsNullOrWhiteSpace(textBoxName.Text))
4. {
5. e.Cancel = true;
6. textBoxName.Focus();
7. errorProviderApp.SetError(textBoxName, "Name should not be left blank!");
8. } else
9. {
10. e.Cancel = false;
11. errorProviderApp.SetError(textBoxName, "");
12. }
13. }

Step 4: Now validation should be triggered on Enter key press. Add following code to Enter key click
method.

1. private void buttonEnter_Click(object sender, EventArgs e)


2. {
3. if (ValidateChildren(ValidationConstraints.Enabled))
4. {
5. MessageBox.Show(textBoxName.Text, "Demo App - Message!");
6. }
7. }

Also make sure that Enter button's "CauseValidation" property should be set to "true".
Now our window form in ready with validation.

ALL RIGHTS RESERVED TO SVTI 51


CHAPTER 08

VISUAL BASIC APPLICATION INTERFACES


Menus
Menus are vital to any application. Depending on the program, the menus enable the user to physically
use your program. The user chooses whichever menu and the program responds accordingly—whether it
is showing a dialog box, or changing the color of the words, or exiting. Menus allow you to arrange
commands in a logical and easy-to-find fashion. A menu shouldn't contain paragraphs of text, or even
long sentences; its sole purpose is to help you navigate through the entire program.

Creating a Menu
1. Click the MenuEditor component at the bottom of the screen. This will allow you to start entering
menu items. Type in Fileand press Enter.
2. You now have a File menu!
3. Click File, then underneath File where it displays text, as shown in Figure 1, type Open.

Repeat the steps to enter the Save, Recent, and Exit items to the File menu.
4. Add a menu item 'Edit' next to File and Add Cut, Copy, and Paste underneath it.
5. Add a Help menu with About, and Online items.

Now that you have the main menu sorted, let's take it a step further and add a submenu to the Open menu
item. To do this, follow these steps:

1. Click the Open menu item.


2. To the right of the Open menu item, you should see the 'Type Here' section.
3. Enter Text.
4. Underneath the Text menu item, enter Other.

Adding Menu Features


Currently, the menus look a bit, well, dull. Let's add some small but significant changes to the menus.
Adding Alt Key Shortcuts
If you do not know what an Alt key shortcut key is, let me explain: An Alt key shortcut enables you to
press the Alt key and then the underlined letter to display the menu. For example: If you press Alt + F, it
should open the File menu. To make a letter in the menu display underlined and act as an Alt key shortcut,
follow these steps:

ALL RIGHTS RESERVED TO SVTI 52


1. Click the desired Menu item.
2. Open the Properties Window.
3. Add an ampersand in front of the desired letter to be used as a shortcut. In Figure, I have added an
ampersand in front of the O in Open.

Adding Keyboard Shortcut Keys to Menus


Shortcut keys are usually a combination of Ctrl and a letter. For example, Ctrl + C is the keyboard shortcut
for Copy and Ctrl + V is the Keyboard shortcut for Paste. To add a keyboard shortcut key to a menu item,
follow these steps:

1. Click the desired Menu Item.


2. Open the Properties Window.
3. Find the Shortcut keys Property.
4. Set the desired Shortcut, as displayed in Figure.

The Shortcut will be displayed next to the Menu item's text.

Adding Icons to Menu Items


To add a small icon next to the Menu Item, follow these easy steps:

1. Click the desired menu item.


2. Open the Properties Window.
3. Select the Icon Property.

Once you click on the button, the Select Resource box will appear. Here, you can select from already
added icons inside your project, or add new items to your project's resources:

ALL RIGHTS RESERVED TO SVTI 53


Adding a Separator Bar Inside the Menu
To Add a Separator bar to your menu, follow these steps:

1. Click the Menu Item that you want to separate from other menu items.
2. When the 'Type Here' text appears, look closely. There is a small drop-down arrow next to it, as shown
in Figure.
3. Select Separator from the displayed list.
Your finished Menus should look like those shown in Figures 6-8.

Figure 6: File Menu

Figure 7: Edit Menu

Figure 8: Help Menu

In case this article isn't long enough already, I have added some basic code…

ALL RIGHTS RESERVED TO SVTI 54


Toolbars
A toolbar is a bar that displays in the top section under the main menu. Here is an example:

A toolbar is a classic control container. It can host text, buttons, etc. It is up to you to decide whether your
application needs a toolbar and what you want to position on it.
start a toolbar, declare a variable of this class. Because a toolbar is hosted by a container, namely a form,
if you want to display it, you should (must) add it to the Controls collection of its host. Here is an example:

Imports System.Windows.Forms

Public Class Exercise


Inherits System.Windows.Forms.Form

Dim tbrStandard As ToolStrip

Public Sub New()


tbrStandard = New ToolStrip

Controls.Add(tbrStandard)
End Sub

<STAThread()>
Public Shared Function Main() As Integer
Application.Run(New Exercise)

Return 0
End Function

End Class
This would produce:

Double-click the toolbar, which will cause the code window to open with the ButtonClick event for the
toolbar, which is the event we want to code for. The Sub procedure header looks like this:

Private Sub tbrMenuOpts_ButtonClick(ByVal Button As MSComctlLib.Button)

ALL RIGHTS RESERVED TO SVTI 55


VB passes a Button object to the event procedure; this button object represents the toolbar button that the
user clicked. To see what button the user clicked, test the Index or Key property of the Button object
(using standard object.property syntax, like "Button.Index" or "Button.Key"). In the sample program,
"Button.Key" is used. The coding is as follows:

Private Sub tbrMenuOpts_ButtonClick(ByVal Button As MSComCtlLib.Button)

Select Case Button.Key


Case "New"
mnuFileNew_Click
Case "Open"
mnuFileOpen_Click
Case "Save"
mnuFileSave_Click
Case "Print"
mnuFilePrint_Click
Case "Help"
mnuHelpAbout_Click
End Select
End Sub

Run the program. When you click on a toolbar button ("Print" for example), the corresponding menu
procedure code should execute:

The Status Bar control


A StatusBar control is a combination of StatusBar panels where each panel can be used to display different
information. For example, one panel can display current application status and other can display date and
other information and so on. A typical StatusBar sits at the bottom of a form.

Creating a StatusBar
tatusBar class represents a StatusBar.
Dim mainStatusBar As New StatusBar()
A StatusBar is a combination of StatusBar panels. StatusBarPanel class represents a StatusBar panel. The
following code snippet creates two panels and adds them to the StatusBar.
ALL RIGHTS RESERVED TO SVTI 56
Dim statusPanel As New StatusBarPanel()
Dim datetimePanel As New StatusBarPanel()
statusPanel.BorderStyle = StatusBarPanelBorderStyle.Sunken
statusPanel.Text = "Application started. No action yet."
statusPanel.ToolTipText = "Last Activity"
statusPanel.AutoSize = StatusBarPanelAutoSize.Spring
mainStatusBar.Panels.Add(statusPanel)
datetimePanel.BorderStyle = StatusBarPanelBorderStyle.Raised
datetimePanel.ToolTipText = "DateTime: " + System.DateTime.Today.ToString()
datetimePanel.Text = System.DateTime.Today.ToLongDateString()
datetimePanel.AutoSize = StatusBarPanelAutoSize.Contents
mainStatusBar.Panels.Add(datetimePanel)

Now, make sure ShowPanels property is true.


mainStatusBar.ShowPanels = True

In the end, we add StatusBar to the Form.

Controls.Add(mainStatusBar)

Now let's create a Windows Forms application with a few controls on it. We are going to show current
activity and date on the status bar. The Form looks like following.

Here bottom of window show the status of Checkbox and show current date.
Some Common Controls in VB.NET Control
VB.NET has a variety of controls, below given are the list of commonly used controls.

Text Box
As you can guess, it is used to accept textual input from the user. The user can add strings, numerical
values and a combination of those, but Images and other multimedia content are not supported.

Example:

ALL RIGHTS RESERVED TO SVTI 57


Public Class Example1
Private Sub Example1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "educba.com"
End Sub
Private Sub btnMessage_Click(sender As Object, e As EventArgs) _
Handles btnMessage.Click
MessageBox.Show("Thanks " + txtName.Text + " from all of us at " + txtOrg.Text)
End Sub
End Class

Label
It is used to show any text to the user, typically the text in a label does not change while the application is
running.

Button
It is used as a standard Windows Button. In most cases, the Button Control is used to generate a click
event, its name, size and appearance are not changed in the runtime.

Example:
Public Class Form1
Private Sub ButtonExmaple_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "educba.com"
End Sub
Private Sub quitBTN _Click(sender As Object, e As EventArgs) Handles quitBTN.Click
Application.Exit()
End Sub
End Class

List Box
As the name suggests, this control works as a way to display a list of items on the application. Users can
select any options from the list.
Example:
Public Class example
Private Sub dropexmaple_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.Items.Add("India")
ListBox1.Items.Add("Pakistan")
ListBox1.Items.Add("USA")
End Sub
Private Sub BTN1_Click(sender As Object, e As EventArgs) Handles BTN1.Click
MsgBox("The country you have selected is " + ListBox1.SelectedItem.ToString())
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
Handles ListBox1.SelectedIndexChanged
Textlable2.Text = ListBox1.SelectedItem.ToString()
End Sub
End Class

ALL RIGHTS RESERVED TO SVTI 58


Combo Box
It is similar to the list but it works as a dropdown for the user. A user can enter both text in the box or he
can click on the downwards aero on the right side and select any item.
Example:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button2.Click


ComboBox1.Items.Clear()
ComboBox1.Items.Add("India")
ComboBox1.Items.Add("USA")
ComboBox1.Items.Add("Japan")
ComboBox1.Items.Add("China")
ComboBox1.Items.Add("Iceland")
ComboBox1.Items.Add("Shri Lanka")
ComboBox1.Items.Add("Bangladesh")
ComboBox1.Text = "Select from..."
End Sub

Radio Button
Radio Button is one of the popular ways of limiting the user to pick just one option. The programmer can
set any of the buttons as default if needed. These buttons are grouped together.
Example:
Public Class example
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Private Sub Example_RadioButton1_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton1.CheckedChanged
Me.BackColor = Color.Black
End Sub
Private Sub Example_RadioButton2_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton2.CheckedChanged
Me.BackColor = Color.White
End Sub
Private Sub Example_RadioButton3_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton3.CheckedChanged
Me.BackColor = Color.Brown
End Sub
End Class

Checkbox
Checkboxes are similar to radio buttons in the way that they are also used in groups, however, a user can
select more than one item in the group.
Example:
Public Class Form1
Private Sub Submit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim msg As String = ""
If ExampleCheckBox1.Checked = True Then
msg = " ExampleCheckBox1 Selected"
End If
If ExampleCheckBox2.Checked = True Then
msg = msg & " ExampleCheckBox2 Selected "
End If

ALL RIGHTS RESERVED TO SVTI 59


If ExampleCheckBox3.Checked = True Then
msg = msg & ExampleCheckBox3 Selected"
End If
If msg.Length > 0 Then
MsgBox(msg & " selected ")
Else
MsgBox("No checkbox have beenselected")
End If
CheckBox1.ThreeState = True
End Sub
End Class

Picture Box
This VB.Net control is used to show images and graphics inside a form. The image can be of any supported
format and we can select the size of the object in the form too.
Example:

Private Sub Submit_Click(sender As Object, e As EventArgs) Handles Submit.Click


ExamplePictureBox1.ClientSize = New Size(500, 500)
ExamplePictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Sub

Scroll Bar
When the content in the form is too large to be shown at once, we can use ScrollBars to let users scroll to
see the remaining content, it can be vertical, horizontal or even both depending on the circumstances.
Example:

Public Class example


Private Sub Example1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
Dim horizontalscroll As HScrollBar
Dim verticalscroll As VScrollBar
horizontalscroll = New HScrollBar()
verticalscroll = New VScrollBar()
horizontalscroll.Location = New Point(15, 300)
horizontalscroll.Size = New Size(185, 20)
horizontalscroll.Value = 10
verticalscroll.Location = New Point(300, 35)
verticalscroll.Size = New Size(20, 180)
horizontalscroll.Value = 50
Me.Controls.Add(horizontalscroll)
Me.Controls.Add(verticalscroll)
Me.Text = "Example"
End Sub
End Class

VB.NET Arrays
An array is a linear data structure that is a collection of data elements of the same type stored on
a contiguous memory location. Each data item is called an element of the array. It is a fixed size of

ALL RIGHTS RESERVED TO SVTI 60


sequentially arranged elements in computer memory with the first element being at index 0 and the last
element at index n - 1, where n represents the total number of elements in the array.
The following is an illustrated representation of similar data type elements defined in the VB.NET array
data structure.

In the above diagram, we store the Integer type data elements in an array starting at index 0. It will continue
to store data elements up to a defined number of elements.
Declaration of VB.NET Array
We can declare an array by specifying the data of the elements followed by parentheses () in the VB.NET.
1. Dim array_name As [Data_Type] ()
In the above declaration, array_name is the name of an array, and the Data_Type represents the
type of element (Integer, char, String, Decimal) that will to store contiguous data elements in the
VB.NET array.
Now, let us see the example to declare an array.
2. 'Store only Integer values
3. Dim num As Integer() or Dim num(5) As Integer
4. 'Store only String values
5. Dim name As String() or Dim name(5) As String
6. ' Store only Double values
7. Dim marks As Double()

Initialization of VB.NET Array


In VB.NET, we can initialize an array with New keyword at the time of declaration. For example,
1. 'Declaration and Initialization of an array elements with size 6
2. Dim num As Integer() = New Integer(5) { }
3. Dim num As Integer() = New Integer(5) {1, 2, 3, 4, 5, 6}
4. Initialize an array with 5 elements that indicates the size of an array
5. Dim arr_name As Integer() = New Integer() {5, 10, 5, 20, 15}
6. Declare an array
7. Dim array1 As Char()
8. array1 = New Char() {'A', 'B', 'C', 'D', 'E'}

Furthermore, we can also initialize and declare an array using the following ways, as shown below.
1. Dim intData() As Integer = {1, 2, 3, 4, 5}
2. Dim intData(5) As Integer
3. Dim array_name() As String = {"Peter", "John", "Brock", "James", "Maria"}
4. Dim misc() as Object = {"Hello friends", 16c, 12ui, "A"c}
5. Dim Emp(0 to 2) As String
6. Emp{0} = "Mathew"
7. Emp(1) = " Anthony"
8. Emp(2) = "Prince"

ALL RIGHTS RESERVED TO SVTI 61


Let's create a program to add the elements of an array in VB.NET programming language.
num_Array.vb
1. Imports System
2. Module num_Array
3. Sub Main()
4. Dim i As Integer, Sum As Integer = 0
5. 'In VB.NET the size of an array is n+1
6. 'Declaration and Initialization of marks() array
7. Dim marks() As Integer = {58, 68, 95, 50, 23, 89}
8. Console.WriteLine(" Marks in 6 Subjects")
9. For i = 0 To marks.Length - 1
10. Console.WriteLine(" Marks {0}", marks(i))
11. Sum = Sum + marks(i)
12. Next
13. Console.WriteLine(" Grand total is {0}", Sum)
14. Console.WriteLine(" Press any key to exit...")
15. Console.ReadKey()
16. End Sub
17. End Module

Output:

ALL RIGHTS RESERVED TO SVTI 62


CHAPTER 09

DATABASE CLIENT APPLICATIONS


VB.Net - Database Access
Applications communicate with a database, firstly, to retrieve the data stored there and present it in a user-
friendly way, and secondly, to update the database by inserting, modifying and deleting data.
Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net framework that is used by
the .Net applications for retrieving, accessing and updating data.

ADO.Net Object Model


ADO.Net object model is nothing but the structured process flow through various components. The object
model can be pictorially described as −

The data residing in a data store or database is retrieved through the data provider. Various components
of the data provider retrieve data for the application and update data.
An application accesses data either through a dataset or a data reader.
 Datasets store data in a disconnected cache and the application retrieves data from it.

 Data readers provide data to the application in a read-only and forward-only mode.
Data Provider
A data provider is used for connecting to a database, executing commands and retrieving data, storing it
in a dataset, reading the retrieved data and updating the database.

The data provider in ADO.Net consists of the following four objects −


Sr.No. Objects & Description
1 Connection
This component is used to set up a connection with a data source.
2 Command
A command is a SQL statement or a stored procedure used to retrieve, insert, delete or
modify data in a data source.
3 DataReader
Data reader is used to retrieve data from a data source in a read-only and forward-only mode.

ALL RIGHTS RESERVED TO SVTI 63


4 DataAdapter
This is integral to the working of ADO.Net since data is transferred to and from a database
through a data adapter. It retrieves data from a database into a dataset and updates the
database. When changes are made to the dataset, the changes in the database are actually
done by the data adapter.

There are following different types of data providers included in ADO.Net


 The .Net Framework data provider for SQL Server - provides access to Microsoft SQL Server.
 The .Net Framework data provider for OLE DB - provides access to data sources exposed by using
OLE DB.
 The .Net Framework data provider for ODBC - provides access to data sources exposed by ODBC.
 The .Net Framework data provider for Oracle - provides access to Oracle data source.
 The EntityClient provider - enables accessing data through Entity Data Model (EDM) applications.

DataSet
DataSet is an in-memory representation of data. It is a disconnected, cached set of records that are
retrieved from a database. When a connection is established with the database, the data adapter creates a
dataset and stores data in it. After the data is retrieved and stored in a dataset, the connection with the
database is closed. This is called the 'disconnected architecture'. The dataset works as a virtual database
containing tables, rows, and columns.

The following diagram shows the dataset object model −

The DataSet class is present in the System.Data namespace. The following table describes all the
components of DataSet –

ALL RIGHTS RESERVED TO SVTI 64


Sr.No. Components & Description

1 DataTableCollection
It contains all the tables retrieved from the data source.

2 DataRelationCollection
It contains relationships and the links between tables in a data set.

3 ExtendedProperties
It contains additional information, like the SQL statement for retrieving data, time of
retrieval, etc.

4 DataTable
It represents a table in the DataTableCollection of a dataset. It consists of the DataRow and
DataColumn objects. The DataTable objects are case-sensitive.

5 DataRelation
It represents a relationship in the DataRelationshipCollection of the dataset. It is used to
relate two DataTable objects to each other through the DataColumn objects.

6 DataRowCollection
It contains all the rows in a DataTable.

7 DataView
It represents a fixed customized view of a DataTable for sorting, filtering, searching, editing
and navigation.

8 PrimaryKey
It represents the column that uniquely identifies a row in a DataTable.

9 DataRow
It represents a row in the DataTable. The DataRow object and its properties and methods
are used to retrieve, evaluate, insert, delete, and update values in the DataTable. The
NewRow method is used to create a new row and the Add method adds a row to the table.

10 DataColumnCollection
It represents all the columns in a DataTable.

11 DataColumn
It consists of the number of columns that comprise a DataTable.

Connecting to a Database
The .Net Framework provides two types of Connection classes −
 SqlConnection − designed for connecting to Microsoft SQL Server.
 OleDbConnection − designed for connecting to a wide range of databases, like Microsoft Access and
Oracle.

Example 1
We have a table stored in Microsoft SQL Server, named Customers, in a database named testDB. Please
consult 'SQL Server' tutorial for creating databases and database tables in SQL Server.

ALL RIGHTS RESERVED TO SVTI 65


Let us connect to this database. Take the following steps −

Select TOOLS → Connect to Database

Select a server name and the database name in the Add Connection dialog box.

Click on the Test Connection button to check if the connection succeeded.

Add a DataGridView on the form.

ALL RIGHTS RESERVED TO SVTI 66


Click on the Choose Data Source combo box.
Click on the Add Project Data Source link.

This opens the Data Source Configuration Wizard.


Select Database as the data source type

Choose DataSet as the database model.

ALL RIGHTS RESERVED TO SVTI 67


Choose the connection already set up.

Save the connection string.

Choose the database object, Customers table in our example, and click the Finish button.

ALL RIGHTS RESERVED TO SVTI 68


Select the Preview Data link to see the data in the Results grid −

When the application is run using Start button available at the Microsoft Visual Studio tool bar, it will
show the following window −

Example 2
In this example, let us access data in a DataGridView control using code. Take the following steps −

ALL RIGHTS RESERVED TO SVTI 69


 Add a DataGridView control and a button in the form.
 Change the text of the button control to 'Fill'.
 Double click the button control to add the required code for the Click event of the button, as shown
below −
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
'TODO: This line of code loads data into the 'TestDBDataSet.CUSTOMERS' table.
You can move, or remove it, as needed.

Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


Dim connection As SqlConnection = New sqlconnection()
connection.ConnectionString = "Data Source=KABIR-DESKTOP; _
Initial Catalog=testDB;Integrated Security=True"
connection.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter _
("select * from Customers", connection)
Dim ds As DataSet = New DataSet()
adp.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
End Sub
End Class

When the above code is executed and run using Start button available at the Microsoft Visual Studio tool
bar, it will show the following window −

 Clicking the Fill button displays the table on the data grid view control −

ALL RIGHTS RESERVED TO SVTI 70


Creating Table, Columns and Rows
We have discussed that the DataSet components like DataTable, DataColumn and DataRow allow us to
create tables, columns and rows, respectively.
The following example demonstrates the concept −

Example 3
So far, we have used tables and databases already existing in our computer. In this example, we will create
a table, add columns, rows and data into it and display the table using a DataGridView object.
Take the following steps −
 Add a DataGridView control and a button in the form.
 Change the text of the button control to 'Fill'.
 Add the following code in the code editor.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub

Private Function CreateDataSet() As DataSet


'creating a DataSet object for tables
Dim dataset As DataSet = New DataSet()
' creating the student table
Dim Students As DataTable = CreateStudentTable()
dataset.Tables.Add(Students)
Return dataset
End Function

Private Function CreateStudentTable() As DataTable


Dim Students As DataTable
Students = New DataTable("Student")
' adding columns
AddNewColumn(Students, "System.Int32", "StudentID")
AddNewColumn(Students, "System.String", "StudentName")
AddNewColumn(Students, "System.String", "StudentCity")
' adding rows
AddNewRow(Students, 1, "Zara Ali", "Kolkata")
AddNewRow(Students, 2, "Shreya Sharma", "Delhi")
AddNewRow(Students, 3, "Rini Mukherjee", "Hyderabad")
ALL RIGHTS RESERVED TO SVTI 71
AddNewRow(Students, 4, "Sunil Dubey", "Bikaner")
AddNewRow(Students, 5, "Rajat Mishra", "Patna")
Return Students
End Function

Private Sub AddNewColumn(ByRef table As DataTable, _


ByVal columnType As String, ByVal columnName As String)
Dim column As DataColumn = _
table.Columns.Add(columnName, Type.GetType(columnType))
End Sub

'adding data into the table


Private Sub AddNewRow(ByRef table As DataTable, ByRef id As Integer,_
ByRef name As String, ByRef city As String)
Dim newrow As DataRow = table.NewRow()
newrow("StudentID") = id
newrow("StudentName") = name
newrow("StudentCity") = city
table.Rows.Add(newrow)
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


Dim ds As New DataSet
ds = CreateDataSet()
DataGridView1.DataSource = ds.Tables("Student")
End Sub
End Class

When the above code is executed and run using Start button available at the Microsoft Visual Studio tool
bar, it will show the following window −

Clicking the Fill button displays the table on the data grid view control −

ALL RIGHTS RESERVED TO SVTI 72


CHAPTER 10

VISUAL BASIC PROJECT DEVELOPMENT CYCLE


Software Development life cycle – SDLC
Software Development Life Cycle (SDLC) is a process used by the software industry to design, develop
and test high quality softwares. The SDLC aims to produce a high-quality software that meets or exceeds
customer expectations, reaches completion within times and cost estimates.
 SDLC is the acronym of Software Development Life Cycle.
 It is also called as Software Development Process.
 SDLC is a framework defining tasks performed at each step in the software development process.
 ISO/IEC 12207 is an international standard for software life-cycle processes. It aims to be the standard
that defines all the tasks required for developing and maintaining software.

The following figure is a graphical representation of the various stages of a typical SDLC.

The Visual Basic Project Lifecycle


In the project initiation phase, a comprehensive project plan is prepared. This plan lists the tasks to be
performed during the life cycle of the project. It also identifies the team members and assigns
responsibilities to them based on their skills. In the project execution phase, the team develops the required
application. Because this is the most elaborate phase in terms of project cost and time, this phase can be
further divided into the following stages:

ALL RIGHTS RESERVED TO SVTI 73


Create a project
First, we'll create a Visual Basic application project. The project type comes with all the template files
you'll need, before you've even added anything!
1. Open Visual Studio.
2. On the start window, choose Create a new project.

In the Create a new project window, choose Visual Basic from the Language list. Next,
choose Windows from the Platform list and Console from the project types list.
After you apply the language, platform, and project type filters, choose the Console Application template,
and then choose Next.

Then, in the Visual Studio Installer, choose the .NET Core cross-platform development workload. After
that, choose the Modify button in the Visual Studio Installer. You might be prompted to save your work;
if so, do so. Next, choose Continue to install the workload. Then, return to step 2 in this "Create a project"
procedure.

In the Configure your new project window, type or enter WhatIsYourName in the Project name box.
Then, choose Next.

ALL RIGHTS RESERVED TO SVTI 74


In the Additional information window, .NET Core 3.1 should already be selected for your target
framework. If not, select .NET Core 3.1. Then, choose Create.

Visual Studio opens your new project.


Create a "What Is Your Name" application

Let's create an app that prompts you for your name and then displays it along with the date and time.
Here's how:
1. In the WhatIsYourName project, enter the following Visual Basic code immediately after the opening
bracket that follows the Sub Main(args As String()) line and before the End Sub line:

VBCopy
Console.WriteLine(vbCrLf + "What is your name? ")
Dim name = Console.ReadLine()
Dim currentDate = DateTime.Now
Console.WriteLine($"{vbCrLf}Hello, {name}, on {currentDate:d} at {currentDate:t}!")
Console.Write(vbCrLf + "Press any key to exit... ")
Console.ReadKey(True)
This code replaces the existing WriteLine, Write, and ReadKey statements.

ALL RIGHTS RESERVED TO SVTI 75


2. Use the green Start button, or press F5 to build and run your first app.
3. When the console window opens, enter your name. Your console window should look similar to the
following screenshot:

4. Press any key to close the console window.


Create a "Calculate This" application
1. On the start window, choose Create a new project.
2. In the Create a new project window, choose Visual Basic from the Language list. Next, choose Win-
dows from the Platform list and Console from the project types list.
3. After you apply the language, platform, and project type filters, choose the Console Application tem-
plate, and then choose Next.
Then, in the Configure your new project window, type or enter CalculateThis in the Project
name box. Then, choose Next.
4. In the Additional information window, .NET Core 3.1 should already be selected for your target
framework. If not, select .NET Core 3.1. Then, choose Create.
5. Enter the following code between the Module Program line and End Module line:

Public num1 As Integer


Public num2 As Integer
Public answer As Integer
Sub Main()
Console.WriteLine("Type a number and press Enter")
num1 = Console.ReadLine()
Console.WriteLine("Type another number to add to it and press Enter")
num2 = Console.ReadLine()
answer = num1 + num2
Console.WriteLine("The answer is " & answer)
Console.ReadLine()
End Sub
Your code window should look like the following screenshot:

ALL RIGHTS RESERVED TO SVTI 76


6. Click CalculateThis to run your program. Your console window should look similar to the following
screenshot:

Deploying VB Applications
First of all, load your application in Visual Basic 2017. In this example, I wish to publish my Draw Text
application. In the VB2017 IDE, choose Build and then select Publish Draw text, as shown in the
following figure.

ALL RIGHTS RESERVED TO SVTI 77


After clicking Publish Draw Text, the Publish Wizard will ask you to choose a location that you want to
publish this application. You may publish the application on your local drive or to a remote location via
FTP, as shown in the following figure:

Click the Next button to continue. Now, the Publish Wizard will ask you how will users install the
application. There are three options, from a website, from a UNC path or file share and from a CD-ROM
or DVD-ROM. In this example, we choose CD-ROM or DVD-ROM, as shown in the following figure:

You may click the Next button to continue with the Publish Wizard or the Finish button to complete the
publishing process. If you click the Next button, the Publish Wizard will ask where will the application

ALL RIGHTS RESERVED TO SVTI 78


check for updates. In our example, we choose that the application will not check for updates, as shown in
the following figure.

After clicking the Next button, the final screen of the Publish Wizard will show you where the application
will be published to.

Upon clicking the Finish button, the installation files and folder will be saved to the specified location. In
our examples, the folder is Application files and the files are Draw text.application and setup.exe. You
may now burn the folder and files into a CD-ROM, DVD-ROM or upload them to a website for
distribution to the users.

ALL RIGHTS RESERVED TO SVTI 79


Designing N-Tier Applications
N-tier architecture is also called multi-tier architecture because the software is engineered to have the
processing, data management, and presentation functions physically and logically separated. That means
that these different functions are hosted on several machines or clusters, ensuring that services are
provided without resources being shared and, as such, these services are delivered at top capacity. The
“N” in the name n-tier architecture refers to any number from 1.
N-tier architecture would involve dividing an application into three different tiers. These would be the

1. logic tier,
2. the presentation tier, and
3. the data tier.

ALL RIGHTS RESERVED TO SVTI 80


CHAPTER 11

USING VISUAL BASIC OBJECTS


Forms
A Form is used in VB.NET to create a form-based or window-based application. Using the form, we can
build a attractive user interface. It is like a container for holding different control that allows the user to
interact with an application. The controls are an object in a form such as buttons,
Textboxes, Textarea, labels, etc. to perform some action. However, we can add any control to the runtime
by creating an instance of it.
A Form uses a System.Windows.Form namespace, and it has a wide family of controls that add both forms
and functions in a Window-based user interface.

The following are the most important list of events related to a form.
Events Description
Activated An activated event is found when the user or program activates the form.
Click A click event is active when the form is clicked.
Closed A closed event is found before closing the form.
Closing It exists when a form is closing.
DoubleClick DoubleClick
The DoubleClick event is activated when a user double clicks on the form.

DragDrop A DragDrop event is activated when a drag and drop operation is performed.
MouseDown A MouseDown event is activated when the mouse pointer is on the form, and the
mouse button is pressed.

GotFocus A GotFocus event is activated when the form control receives a focus.
HelpButtonClicked It is activated when a user clicked on the help button.
KeyDown A KeyDown event is activated when a key is pressed while focussing on the
form.
KeyUp A KeyUp event is activated when a key is released while focusing on the form.
Load The load event is used to load a form before it is first displayed.
LostFocus It is activated when the form loses focus.
MouseEnter A MouseEnter event is activated when the mouse pointer enters the form.
MouseHover A MouseHover event is activated when the mouse pointer put on the form.
MouseLeave A MouseLeave event is activated when the mouse pointer leaves the form
surface.
Shown It is activated whenever the form is displayed for the first time.
Scroll A Scroll event is activated when a form is scrolled through a user or code.
Resize A Resize event is activated when a form is resized.
Move A Move event is activated when a form is moved.

ALL RIGHTS RESERVED TO SVTI 81


For creating a Windows Forms application in VB.NET, we need to follow the following steps in
Microsoft Visual Studio.
1. GoTo File Menu.
2. Click on New Project.
3. Click on Windows Forms App or Application

And finally, click on the 'Create' button to create your project, and then, it displays the following window
form with a name Form1.

Now create a simple program of Windows form control in VB.NET.


Form1.vb
1. Public Class Form1
2. ' Create nameStr and num variables
3. Dim nameStr As String
4. Dim num As Integer
5. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Loa
6. End Sub
7. ' It is Label1
8. Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
9. End Sub
10. ' It is TextBox1 for inserting the value.
11. Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.Tex
tChanged
12. End Sub
13. ' It is Label2
14. Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
15. End Sub
16. ' It is a Button1 for transferring the control.
17. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
18. nameStr = TextBox1.Text
19. num = TextBox2.Text
20. Label3.Text = "You have entered the Name " & nameStr + " Number " & num

ALL RIGHTS RESERVED TO SVTI 82


21. End Sub
22. ' It is TextBox2 for inserting the value.
23. Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.Tex
tChanged
24. End Sub
25. ' It is label3
26. Private Sub Label3_Click(sender As Object, e As EventArgs) Handles Label3.
27. End Sub
28. End Class
Output:

Now enter the following details in the form:

After filling all the details, click on the Submit button. After that, it shows the following Output:

ALL RIGHTS RESERVED TO SVTI 83


CHAPTER 12

DIALOG LAYOUT
Laying Out a Dialog Interface
 All controls within a utility dialog should start at the top/left and flow downward.
 Never center controls on a dialog to fill a large area.
 Use the environment font for all dialog text. When writing a visual spec, specify the environment font
instead of selecting a particular font and size. See The environment font.
 Use consistent control spacing and placement to support the goal for quality in craftsmanship.
 Dialogs can become more complex from a larger number of controls, a unique juxtaposition of
controls, or both. For those complex situations, allow adequate space between control groupings to
give the user a logical flow to parse.

Dialog layout examples


All dimensions are expressed as pixels.

ALL RIGHTS RESERVED TO SVTI 84


Control indentation
When controls are nested, align inner controls horizontally with the left edge of the control above, usually
the label.

Working with Frames and Tab order.


Navigation Frame and Tab Pane controls are simple controls that create single document interface (SDI)
and share most concepts and features.

Both controls are populated and customized in the very same way. At design time, when a control is
focused, a navigation toolbar contains buttons to add a new page or remove the currently active page (see
below). Arrow buttons allow users to navigate through pages. The index of the currently displayed page
is shown on the toolbar’s left side.

ALL RIGHTS RESERVED TO SVTI 85


Private Sub navigationFrame1_QueryControl(ByVal sender As Object, ByVal e As
DevExpress.XtraBars.Navigation.QueryControlEventArgs)
e.Control = New Label() With {.BackColor = Color.Teal, .Dock = DockStyle.Fill, .Text = "Sample
Content", .AutoSize = False, .TextAlign = ContentAlignment.MiddleCenter}
End Sub
Dialog Hot/Shortkeys

Dialog tools , techniques and validation control.


There are the commonly used dialog box tools are.

1. Color Dialog Box: It is used to display the color dialog box that allows the user to select a color from
the predefined colors or specify the custom colors.
2. Font DialogBox: It is used to create a Font dialog box that allows the user to select the font, font size,
color, and style to be applied to the current text selection.
3. OpenFile Dialog Box: It is used to create a prompt box that allows the users to select a file to open
and allows the selection of multiple files.
4. Print Dialog Box: It is used to create a print dialog box that allows the user to print documents by
selecting the printer and setting of the page printed through the Windows application.

ALL RIGHTS RESERVED TO SVTI 86


Let's create a simple program to display the dialog box in the VB.NET Windows Forms.

Dialog.vb

1. Public Class Dialog


2. Private Sub Dialog_Load(sender As Object, e As EventArgs) Handles MyBase.Load
3. Button1.Text = "Click Me" 'Set the name of button
4. Me.Text = "javatpoint.com" ' Set the title name for the Windows Form
5. Button1.BackColor = Color.Green ' Background color of the button
6. End Sub
7. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
8. Dim result1 As DialogResult = MessageBox.Show("Is VB.NET programming language easy to l
earn?",
9. "Important Question",
10. MessageBoxButtons.YesNo)
11. End Sub
12. End Class
Output:

Now, click on the Click Me button show you validation for confirmation , it displays the dialog box, as
shown below.

ALL RIGHTS RESERVED TO SVTI 87


CHAPTER 13

DATA DECLARATIONS
Scope in Visual Basic Programs
Scope, in programming terms, refers to the visibility of assets. These assets include variables, arrays,
functions, classes, and structures. Visibility in this case means which parts of your program can see or use
it.
Essentially, there are four levels of scope in Visual Basic. These are:

 Block scope: Available only within the code block in which it is declared
 Procedure scope: Available to all code within the procedure in which it is declared
 Module scope: Available to all code within the module, class, or structure in which it is declared
 Namespace scope: Available to all code in the namespace in which it is declared

Block Scope
A block is a set of statements enclosed within starting and ending declaration statements, such as the
following:
 If and End If
 Select and End Select
 Do and Loop
 While and End While
 For [Each] and Next
 Try and End Try
 With and End With
If you declare a variable within a block, such as the above-mentioned examples, you can use it only within
that block. In the following example, the scope of the SubTotal variable is the block between the If and
End If statements. Because the variable SubTotal has been declared inside the block, you cannot refer to
SubTotal when execution passes out of the block.
1. If Tax > 15.0 Then
2. Dim SubTotal As Decimal
3. SubTotal = Tax * SubTotal 'Correct'
4. End If
5. 'Wrong. Will Not Work Because SubTotal is Out of Scope!'
6. MessageBox.Show(SubTotal.ToString())

Procedure Scope
Procedure scope refers to an an element that is declared within a procedure is not available outside that
procedure. Only the procedure that contains the declaration can use it. Variables at this level are usually
known as local variables.
In the following example, the variable strWelcome declared in the ShowWelcome Sub procedure cannot
be accessed in the Main Sub procedure:
1. Sub Main()
2. ShowWelcome()
3. Console.WriteLine(strWelcome) 'Will not work!'
4. Console.WriteLine("Press Enter to continue...")
5. Console.ReadLine()
6. End Sub
7. Sub ShowWelcome()]
8. Dim strWelcome = "Hello friend"

ALL RIGHTS RESERVED TO SVTI 88


9. Console.WriteLine(strWelcome)
10. End Sub

Module Scope
You can declare elements at the Module level by placing the declaration statement outside of any
procedure or block but within the module, class, or structure. When you create a variable at module level,
the access level you choose determines the scope. More on Access Modifiers later.

Private elements are available to every procedure in that particular module, but not to any code in a
different module.
In the following example, all procedures defined in the module can refer to the string variable strWelcome.
When the second procedure is called, it displays the contents of the string variable strWelcome in a
messagebox.
1. Private strWelcome As String 'Outside of all Procedures'
2. Sub StoreWelcomeGreeting()
3. strWelcome = "Welcome to the world of Programming"
4. End Sub
5.
6. Sub SayWelcome()
7. MessageBox.Show(strWelcome)
8. End Sub

Namespace Scope
Namespace scope can be thought of as project scope. By declaring an element at module level using either
the Friend or Public keyword, it becomes available to all procedures throughout the namespace in which
the element is declared. An element available from within a certain namespace also is available from
within any namespaces that are nested inside that namespace. Public elements in a class, module, or
structure are available to any project that references their project, as well.
If I had changed the declaration of strWelcome (from the previous example) to:

1. Public strWelcome As String 'Outside of all Procedures'


strWelcome would have been accessible throughout the entire namespace.

VB.NET Variable , Constant and Datatypes.


In VB.NET, a variable is used to hold the value that can be used further in the programming. In this
section, we will learn how to declare and initialize a variable and a constant.

What is a Variable?
A variable is a simple name used to store the value of a specific data type in computer memory.
In VB.NET, each variable has a particular data type that determines the size, range, and fixed space in
computer memory. With the help of variable, we can perform several operations and manipulate data
values in any programming language.
VB.NET Variables Declaration
The declaration of a variable is simple that requires a variable name and data type followed by a Dim. A
Dim is used in Class, Module, structure, Sub, procedure.
Syntax:
1. Dim [Variable_Name] As [Defined Data Type]

ALL RIGHTS RESERVED TO SVTI 89


Name Descriptions
Dim It is used to declare and allocate the space for one or more variables in memory.
Variable_Name It defines the name of the variable to store the values.
As It is a keyword that allows you to define the data type in the declaration statement.
Data Type It defines a data type that allows variables to store data types such as Char, String,
Integer, Decimal, Long, etc.

Value Assign a value to the variable.

There are some valid declarations of variables along with their data type definition, as shown below:
1. Dim Roll_no As Integer
2. Dim Emp_name As String
3. Dim Salary As Double
4. Dim Emp_id, Stud_id As Integer
5. Dim result_status As Boolean

Further, if we want to declare more than one variable in the same line, we must separate each variable
with a comma.
Syntax
1. Dim Variable_name1 As DataType1, variable_name2 As DataType2, Varia-
ble_name3 As DataType3
Note: The statements given below is also used to declare the variable with their data type:
1. Static name As String
2. Public bill As Decimal = 0

VB.NET Variable Initialization


After the declaration of a variable, we must assign a value to the variable. The following syntax describes
the initialization of a variable:
Syntax:
1. Variable_name = value
For example:
1. Dim Roll_no As Integer 'declaration of Roll_no
2. Roll_no = 101 'initialization of Roll_no
3. Initialize the Emp_name
4. Dim Emp_name As String
5. Emp_name = "David" 'Here Emp_name variable assigned a value of David
6. Initialize a Boolean variable
7. Dim status As Boolean 'Boolean value can be True or False.
8. status = True 'Initialize status value to True

ALL RIGHTS RESERVED TO SVTI 90


We can also initialize a variable at the time of declaration:
1. Dim Roll_no As Integer = 101
2. Dim Emp_name As String = " Stephen Robert "

Let's create a program to use different types of variable declaration and initialization in VB.NET.
Variable1.vb
1. Imports System
2. Module Variable1
3. Sub Main()
4. 'declaration of intData as Integer
5. Dim intData As Integer
6. 'declaration of charData as Char
7. Dim CharData As Char
8. 'declaration of strData as String
9. Dim strData As String
10. 'declaration of dblData as Double
11. Dim dblData As Double
12. 'declaration of single_data as Single
13. Dim single_data As Single
14. 'Initialization of intData
15. intData = 10
16. 'Initialization of CharData
17. CharData = "A"
18. 'Initialization of strData
19. strData = " VB.NET is a Programming Language."
20. dblData = 4567.676
21. 'Initialization of dblData
22. 'Initialization of single_data
23. single_data = 23.08
24. Console.WriteLine(" Value of intData is: {0}", intData)
25. Console.WriteLine(" Value of CharData is: {0}", CharData)
26. Console.WriteLine(" Value of strData is: {0}", strData)
27. Console.WriteLine(" Value of dblData is: {0}", dblData)
28. Console.WriteLine(" Value of single_data is: {0}", single_data)
29. Console.WriteLine("press any key to exit...")
30. Console.ReadKey()
31. End Sub
32. End Module

Output:
Value of intData is: 10
Value of CharData is: A
Value of strData is: VB.NET is a Programming Language.
Value of dblData is: 4567.676
Value of single_data is: 23.08
press any key to exit...

ALL RIGHTS RESERVED TO SVTI 91


CHAPTER 14

LOGIC AND ITERATION


Logic Statements
Following table shows all the logical operators supported by VB.Net. Assume variable A holds Boolean
value True and variable B holds Boolean value False, then −
Operator Description Example
And It is the logical as well as bitwise AND operator. If both the operands are (A And B) is
true, then condition becomes true. This operator does not perform short- False.
circuiting, i.e., it evaluates both the expressions.
Or It is the logical as well as bitwise OR operator. If any of the two operands is (A Or B) is
true, then condition becomes true. This operator does not perform short- True.
circuiting, i.e., it evaluates both the expressions.
Not It is the logical as well as bitwise NOT operator. Used to reverse the logical Not(A And
state of its operand. If a condition is true, then Logical NOT operator will B) is True.
make false.
Xor It is the logical as well as bitwise Logical Exclusive OR operator. It returns A Xor B is
False if both expressions are True or both expressions are False; otherwise, True.
it returns True. This operator does not perform short-circuiting, it always
evaluates both expressions and there is no short-circuiting counterpart of this
operator
AndAlso It is the logical AND operator. It works only on Boolean data. It performs (A AndAlso
short-circuiting. B) is False.
OrElse It is the logical OR operator. It works only on Boolean data. It performs (A OrElse
short-circuiting. B) is True.
IsFalse It determines whether an expression is False.
IsTrue It determines whether an expression is True.

Try the following example to understand all the logical/bitwise operators available in VB.Net −
Module logicalOp
Sub Main()
Dim a As Boolean = True
Dim b As Boolean = True
Dim c As Integer = 5
Dim d As Integer = 20
'logical And, Or and Xor Checking

If (a And b) Then
Console.WriteLine("Line 1 - Condition is true")
End If
If (a Or b) Then
Console.WriteLine("Line 2 - Condition is true")
End If
If (a Xor b) Then
Console.WriteLine("Line 3 - Condition is true")
End If
'bitwise And, Or and Xor Checking
If (c And d) Then

ALL RIGHTS RESERVED TO SVTI 92


Console.WriteLine("Line 4 - Condition is true")
End If
If (c Or d) Then
Console.WriteLine("Line 5 - Condition is true")
End If
If (c Or d) Then
Console.WriteLine("Line 6 - Condition is true")
End If
'Only logical operators
If (a AndAlso b) Then
Console.WriteLine("Line 7 - Condition is true")
End If
If (a OrElse b) Then
Console.WriteLine("Line 8 - Condition is true")
End If

' lets change the value of a and b


a = False
b = True
If (a And b) Then
Console.WriteLine("Line 9 - Condition is true")
Else
Console.WriteLine("Line 9 - Condition is not true")
End If
If (Not (a And b)) Then
Console.WriteLine("Line 10 - Condition is true")
End If
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is true
Line 4 - Condition is true
Line 5 - Condition is true
Line 6 - Condition is true
Line 7 - Condition is true
Line 8 - Condition is true
Line 9 - Condition is not true
Line 10 - Condition is true

Conditional Constructs (If/Then, Select Case)


Decision making structures require that the programmer specify one or more conditions to be evaluated
or tested by the program, along with a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is determined to
be false.
Following is the general form of a typical decision making structure found in most of the programming
languages −

ALL RIGHTS RESERVED TO SVTI 93


VB.Net provides the following types of decision making statements. Click the following links to check
their details.
Statement Description
If ... Then statement An If...Then statement consists of a boolean expression followed by one or
more statements.
If...Then...Else An If...Then statement can be followed by an optional Else statement,
statement which executes when the boolean expression is false.
nested If statements You can use one If or Else if statement inside another If or Else
if statement(s).
Select Case statement A Select Case statement allows a variable to be tested for equality against a
list of values.
nested Select Case You can use one select case statement inside another select
statements case statement(s).

ALL RIGHTS RESERVED TO SVTI 94


Iteration (Do Loop, For Loop)
There may be a situation when you need to execute a block of code several number of times. In general,
statements are executed sequentially: The first statement in a function is executed first, followed by the
second, and so on.
Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is
the general form of a loop statement in most of the programming languages −

VB.Net provides following types of loops to handle looping requirements. Click the following links to
check their details.
Loop Type Description
Do Loop It repeats the enclosed block of statements while a Boolean condition is True or until
the condition becomes True. It could be terminated at any time with the Exit Do
statement.

For...Next It repeats a group of statements a specified number of times and a loop index counts
the number of loop iterations as the loop executes.
For Each...Next It repeats a group of statements for each element in a collection. This loop is used for
accessing and manipulating all elements in an array or a VB.Net collection.
While... End It executes a series of statements as long as a given condition is True.
While
With... End It is not exactly a looping construct. It executes a series of statements that repeatedly
With refer to a single object or structure.
Nested loops You can use one or more loops inside any another While, For or Do loop.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.
VB.Net provides the following control statements. Click the following links to check their details.

ALL RIGHTS RESERVED TO SVTI 95


Control Statement Description

Exit statement Terminates the loop or select case statement and transfers execution to
the statement immediately following the loop or select case.

Continue statement Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.

GoTo statement Transfers control to the labeled statement. Though it is not advised to
use GoTo statement in your program.

While Loop Example

Do-While Example

ALL RIGHTS RESERVED TO SVTI 96


For Loop Example

For-Each Example

Loop Background and Processing

ALL RIGHTS RESERVED TO SVTI 97


CHAPTER 15

DEBUGGING AND ERROR HANDLING


Types of Errors and Error Handling
In Visual Basic, errors fall into one of three categories: syntax errors, run-time errors, and logic errors.

Debugging application

Syntax Errors
Syntax errors are those that appear while you write code. If you're using Visual Studio, Visual Basic
checks your code as you type it in the Code Editor window and alerts you if you make a mistake, such as
misspelling a word or using a language element improperly. If you compile from the command line, Visual
Basic displays a compiler error with information about the syntax error. Syntax errors are the most
common type of errors. You can fix them easily in the coding environment as soon as they occur.

Run-Time Errors
Run-time errors are those that appear only after you compile and run your code. These involve code that
may appear to be correct in that it has no syntax errors, but that will not execute. For example, you might
correctly write a line of code to open a file. But if most the file does not exist, the application cannot open
the file, and it throws an exception. You can fix run-time errors by rewriting the faulty code or by
using exception handling, and then recompiling and rerunning it.

Logic Errors
Logic errors are those that appear once the application is in use. They are most often faulty assumptions
made by the developer, or unwanted or unexpected results in response to user actions. For example, a
mistyped key might provide incorrect information to a method, or you may assume that a valid value is
always supplied to a method when that is not the case. Although logic errors can be handled by
using exception handling (for example, by testing whether an argument is Nothing and throwing
an ArgumentNullException), most commonly they should be addressed by correcting the error in logic
and recompiling the application.

ALL RIGHTS RESERVED TO SVTI 98


CHAPTER 16

APPLICATION FRAMEWORKS
SDI and MDI Applications

Display application lifecycle


Microsoft Foundation Class (MFC) makes it easy to work with both single-document interface (SDI) and
multiple-document interface (MDI) applications.

SDI applications allow only one open document frame window at a time. MDI applications allow multiple
document frame windows to be open in the same instance of an application.

An MDI application has a window within which multiple MDI child windows, which are frame windows
themselves, can be opened, each containing a separate document. In some applications, the child windows
can be of different types, such as chart windows and spreadsheet windows. In that case, the menu bar can
change as MDI child windows of different types are activated.

I/O and Persistence


Visual Basic File Access
The My.Computer.FileSystem object provides tools for working with files and folders. Its properties,
methods, and events allow you to create, copy, move, investigate, and delete files and
folders. My.Computer.FileSystem provides better performance than the legacy functions
(FileOpen, FileClose, Input, InputString, LineInput, etc.) that are provided by Visual Basic for backward
compatibility.
In This Section
 Reading from Files: Lists topics dealing with using the My.Computer.FileSystem object to read
from files.
 Writing to Files: Lists topics dealing with using the My.Computer.FileSystem object to write to
files.
 Creating, Deleting, and Moving Files and Directories: Lists topics dealing with using
the My.Computer.FileSystem object to creating, copying, deleting and moving files and folders.
 Parsing Text Files with the TextFieldParser Object: Discusses how to use the Text-
FieldReader to parse text files such as logs.
 File Encodings: Describes file encodings and their use.

ALL RIGHTS RESERVED TO SVTI 99


 Walkthrough: Manipulating Files and Directories in Visual Basic: Demonstrates how to create
a utility that reports information about files and folders.
 Troubleshooting: Reading from and Writing to Text Files: Lists common problems encoun-
tered when reading and writing to text files, and suggests remedies for each.

File I/O Commands


Open File for I/O Open "c:\filename.tst" For Input As 3
fn = FreeFile ' next unused number
Open "c:\filename.tst" For Input As fn

Get File Mode temp = FileAttr (3, 1)

Write to File Write 3,

Write to File Print 3,

Read From File Input 3,

Read From File Get 3,

Read From File Line Input #FileHandle, TextLine$

Current Location tempNum = Seek (3)

Current Location tempNum = Loc (3)

Length of File tempNum = LOF(3)

End of File Do While Not EOF(3) .. Loop

Close File Close 3

Closes All Files Reset

File System Objects


The File System Object (FSO) object model provides an object-based tool for working with folders and
files. Using "object.method" syntax, it exposes a comprehensive set of properties and methods to perform
file system operations such as creating, moving, deleting, and providing information about folders and
files. The FSO also provides methods for reading and writing sequential text files, however it does NOT
have methods for processing binary or random files. You can also use "late binding" by declaring the FSO
variable as a generic "object" and then using the "CreateObject" method to instantiate it later, as shown
below. This is the slowest method, but it is the way it must be done in VBScript. The "Scripting." qualifier
is required here.

Dim objFSO As Object


...
Set objFSO = CreateObject("Scripting.FileSystemObject")

The tables below show the various objects, properties, and methods available with the FSO.

ALL RIGHTS RESERVED TO SVTI 100


FSO Objects

Object Description
FileSystemObject The FSO itself, highest level of the FSO object model. Allows the
programmer to interact with Files, Folders and Drives. The programmer
can use the FSO objects to create directories, move files, determine whether
or not a Drive exists, etc.
Drive The Drive object is used to examine information on disk, CD-ROM, RAM
disk, and network drives; the Drives collection provides a list of physical
and logical drives on the system.
File object The File object is used to examine and manipulate files;
the Files collection provides a list of files in a folder.
Folder object The Folder object is used to examine and manipulate folders;
the Folders collection provides a list of subfolders in a folder.
TextStream object Used to read and write text files.

The Registry
When programming in Visual Basic, you can choose to access the registry by means of either the functions
provided by Visual Basic or the registry classes of .NET. The registry hosts information from the operating
system as well as information from applications hosted on the machine. Working with the registry may
compromise security by allowing inappropriate access to system resources or protected information.

In This Section
How to: Create a Registry Key and Set Its Value:
Describes how to use the CreateSubKey and SetValue methods of the My.Computer.Registry object to
create a registry key and set its value.

How to: Read a Value from a Registry Key:


Describes how to use the GetValue method of the My.Computer.Registry object to read a value from a
registry key.
How to: Delete a Registry Key:
Describes how to use the DeleteSubKey method of the My.Computer.Registry.CurrentUser property to
delete a registry key.

Reading from and Writing to the Registry Using the Microsoft.Win32 Namespace:
Describes how to use the Registry and RegistryKey classes of .NET to access the registry.

Security and the Registry: Discusses security issues involving the registry.

ALL RIGHTS RESERVED TO SVTI 101


CHAPTER 17

DEPLOYING APPLICATIONS
The Packaging and Deployment Wizard
Visual Studio .NET provides you the ability to deploy your applications easily. If you click File->Add
Project->New Project, that brings up the template dialog in which you can create a deployment project.
As you can see in Figure, you can choose from a few different types of deployment options.

Packages in Visual Studio .NET


You have two options for packaging your software in Visual Studio .NET: cabinet files and Windows
Installer files.

Cabinet Files
Cabinet files (or .cab files) are compressed files of your existing files. A few restrictions apply to using
.cab files. First of all, your .cab file can contain only one assembly, so a .cab is good if you are distributing
a single DLL component or single executable program. Also a .cab file must have the same name as the
assembly it is packaging. For example, our SmileyFace.dll cabinet file would have to be named
SmileyFace.cab.

Microsoft Windows Installer Files


Microsoft Windows Installer files (or .msi files) are probably the preferred method of installation. The
Windows Installer is the standard installer used for Microsoft Windows 2000, Me, and XP (as well as 98
and even 95). Windows Installer not only installs the application, but it keeps a record of everything it
installs including file and registry information. You can also use Windows Installer to repair an application
since Installer has a record of what it needs and does a check on what it is missing.

Merge Modules
Merge modules (or .msm files) are used in conjunction with .msi files to install components. The merge
module contains all of the file and registry information needed to install your component and can be shared
with different .msi files that also need to install the component. Merge modules are useful because they

ALL RIGHTS RESERVED TO SVTI 102


handle the versioning problem each time you create a new .msm file for later versions of your component.
In general, you would create a merge module for installing a component that may be used for several
different applications.

Setup Project
The setup project allows you to create an .msi file that will install all the necessary files onto a system for
running your application. Once you've created your project, you'll need to add files to the project. If you
right-click on the setup project and choose Add->File, you can add the files you need to deploy. See Figure
26.6.

You also need to bring up the Configuration Manager (under Build->Configuration Manager) to tell it to
compile your setup project by checking the Build button.

Once you have added the files you want to deploy (executable files and other assemblies, graphics files,
readme files, Help files, even source code if you wish), choose Build Solution from the Build menu.
This will create up to five files: Setup.exe, Setup2.msi, setup.ini, InstMsiA.exe, and InstMsiW.exe.
These files are everything you need to deploy your application on another system. The files include the
distributable runtime and all other dependencies. In other words, we can take the files created by the
deployment build, burn them on a CD, bring them to a computer that doesn't have the .NET Framework
installed, and run setup.exe to install the application with all the necessary files.

ALL RIGHTS RESERVED TO SVTI 103


Using the Setup Wizard
The Setup Wizard steps you through creating a deployment package for all the permutations of
deployment file options: .cab file, merge module, Windows setup, and Web setup. It makes the setup
process even easier than shown in the previous example because it tells you exactly what to do. Figure
shows the screen from the Setup Wizard with all the deployment options.

Setup Wizard for Choosing Project Type

The next screen allows us to include outputs from existing projects. This includes primary output such
as the executable file or the component, documentation, source code, debug information files, Help files,
localized assemblies, and even other setup files referenced in this project.

Setup Wizard for Choosing Project Output

Finally, we need to choose any additional miscellaneous files we are interested in for this project such as
a readme file, graphic and sound files, or HTML files. Don't worry if you forget to add files here,
because you can always add them later in the Solution Explorer by rightclicking on the setup project and
choosing Add->File.

Setup Wizard for Choosing Additional Files

ALL RIGHTS RESERVED TO SVTI 104


When you finish with the wizard, it creates a setup file in a separate setup directory. The setup directory
contains the setup.exe and the .msi file to install. When you run setup.exe for the first time, the
screen appears with the name of the setup project shown in the title.

Setup Screen When Running Installation

Setup will install the project into the directory c:\program files\<name of your company>\SetupName\.

The File System View


The File System view shows you where your files will be installed. You can use this view to set up
additional setup options, such as putting your program in the Start menu or on the desktop.

Putting Your File in the Start Menu

To place the program in the Start menu, first bring up the File System view by double-clicking a project
output in the setup project in the Solution Explorer.

File System View in the Deployment Project

ALL RIGHTS RESERVED TO SVTI 105


Now go into the User's Programs menu and right-click in the left-hand pane on the User's Programs
menu to add a folder to the Programs menu. Name the folder after the name of your application.

Adding a Folder to the Start Menu

Now we need to add a shortcut to the application inside the folder. Right-click in the right-hand pane
and choose Create New Shortcut.

Creating the Shortcut in the Application Folder

This brings up the Select Item in Project dialog. Click all the way down into the project folder you just
created.

Adding a Shortcut in the User's Programs Folder

Double-click the Application folder to find the shortcut for the application.

ALL RIGHTS RESERVED TO SVTI 106


Adding a Shortcut from the Application Folder

Look for the application you want to install a shortcut for and click on the Add File button.
Finding the File for the Shortcut

Shortcut in File System Window

In most cases you want to add to the Program menu the application's executable file as well as a readme
file or any Help files and documentation associated with the application. After the deployment project has
been compiled and setup has been run, the application will appear in the Programs menu as shown in
Figure.

Application Appearing in the Start Menu

ALL RIGHTS RESERVED TO SVTI 107


CHAPTER 18

MICROSOFT SQL SERVER 2016


What is data?
Data is simply facts or figures or bit of information , but not information itself.
What is Information?
What data are processed, interpreted, organized, structure or presented so as to makes them meaningful or
useful they are called information.
Data vs Information
Data is the collection of raw facts collected from any
specific environment for a specific purpose. Data in
itself does not show anything about its environment,
so to get desired types of results from the data we
transform it into information by applying certain
processing on it. Once we have processed data using
different methods data is converted into meaningful
form and that form of the Data is called information

What is Database?
A database is an organized collection of information, which can be used alone, or combined / related to
other data for multiple purposes. Database is made up of files, records and field.
For example: if we have data about marks obtained by all students, we can then conclude about toppers
and average marks.
Database Management System
A database management system (DBMS) is software of collection of small programs that enables to store,
modify, and extract information from a database.
DBMS examples include MySQL, Microsoft Access,SQL Server, FileMaker, Oracle, RDBMS.

Database management system (dbms):

 The database management system (DBMS), on the other hand is the software or tool that is used to
manage the database and its users.
 A DBMS consist of different components or subsystems.
 Each subsystem or component of the DBMS performs different function(s), so a DBMS is collection
of different programs but they all work jointly to manage the data stored in the database and its users.
 Sometimes another term is used, that is, the DATABASE SYSTEM , again, this term has been used
differently by different people, however in this subject we use the term database system as a
combination of database and the database management system.
 So database is collection of data, DBMS is tool to manage this data, and both jointly are called
DATABASE SYSTEM.
Introduction to relational database
A relational database is a collection of information that organizes data points with defined relationships
for easy access. In the relational database model, the data structures -- including data tables, indexes and
views -- remain separate from the physical storage structures, enabling database administrators to . the
physical data storage without affecting the logical data structure.

ALL RIGHTS RESERVED TO SVTI 108


In the enterprise, relational databases are used to organize data and identify relationships between key data
points. They make it easy to sort and find information, which helps organizations make business decisions
more efficiently and minimize costs. They work well with structured data.
How does a relational database work?
The data tables used in a relational database store information about related objects. Each row holds a
record with a unique identifier -- known as a key -- and each column contains the attributes of the data.
Each record assigns a value to each feature, making relationships between data points easy to identify.
The standard user and application program interface (API) of a relational database is the Structured Query
Language. SQL code statements are used both for interactive queries for information from a relational
database and for gathering data for reports. Defined data integrity rules must be followed to ensure the
relational database is accurate and accessible.

What is the structure of a relational database model?


E. F. Codd, then a young programmer at IBM, invented the relational database in 1970. In his paper, "A
Relational Model of Data for Large Shared Data Banks," Codd proposed shifting from storing data in
hierarchical or navigational structures to organizing data in tables containing rows and columns.
Each table, sometimes called a relation, in a relational database contains one or more data categories in
columns or attributes. Each row, also called a record or tuple, contains a unique instance of data -- or key -
- for the categories defined by the columns. Each table has a unique primary key that identifies the
information in a table. The relationship between tables can be set via the use of foreign keys -- a field in
a table that links to the primary key of another table.

A relational database includes tables containing rows and columns.


For example, a typical business order entry database would include a table that describes a customer with
columns for name, address, phone number and so forth. Another table would describe an order, including
information like the product, customer, date and sales price.

A user can get a database report showing the data they need. For example, a branch office manager might
want a report on all customers that bought products after a certain date. A financial services manager in
the same company could, from the same tables, obtain a report on accounts that need to be paid.
When creating a relational database, users define the domain of possible values in a data column and
constraints that may apply to that data value. For example, a domain of possible customers could allow
up to 10 possible customer names, but it is limited in one table to allowing only three of these customer
names to be specifiable.
Two constraints relate to data integrity and the primary and foreign keys:

 Entity integrity ensures that the primary key in a table is unique and the value is not set to null.
 Referential integrity requires that every value in a foreign key column will be found in the primary
key of the table from which it originated.

ALL RIGHTS RESERVED TO SVTI 109


In addition, relational databases possess physical data independence. This refers to a system's capacity to
make changes to the inner schema without altering the external schemas or application programs. Inner
schema alterations may include the following:
 The use of new storage devices;
 Modifying indexes;
 Changing from a specific access method to a different one;
 Using different data structures; and
 Using various storage structures or file organizations.

Logical data independence is a system's ability to manage the conceptual schema without altering the
external schema or application programs. Conceptual schema alterations may include the addition or
deletion of new relationships, entities or attributes without altering existing external schemas or rewriting
application programs.

Types of databases
There are several database categories, from basic flat files that aren't relational to NoSQL and
newer graph databases that are considered even more relational than standard relational databases. Some
database types include the following:
Flat file database. These databases consist of a single table of data that has no interrelation -- typically text
files. This type of file enables users to specify data attributes, such as columns and data types.

Find out about the advantages and disadvantages of flat file and relational databases.

NoSQL database. This type of database is an alternative that's especially useful for large, distributed data
sets. NoSQL databases support a variety of data models, including key-value, document, columnar and
graph formats.

Graph database. Expanding beyond traditional column- and row-based relational data models; this
NoSQL database uses nodes and edges that represent connections between data relationships and can
discover new relationships between the data. Graph databases are more sophisticated than relational
databases. They are used for fraud detection or web recommendation engines.

ALL RIGHTS RESERVED TO SVTI 110


Object relational database (ORD)
An ORD is composed of both a relational database management system (RDBMS) and an object-oriented
database management system (OODBMS). It contains characteristics of both the RDBMS and OODBMS
models. A traditional database is used to store the data. It is then accessed and manipulated using queries
written in a query language, such as SQL. Therefore, the basic approach of an ORD is based on a relational
database.

However, an ORD can also be considered object storage, particularly for software written in the object-
oriented programming language, thus pulling on object-oriented characteristics. In this situation, APIs are
used in the storage and retrieval of data.

ALL RIGHTS RESERVED TO SVTI 111


What are the advantages of relational databases?
The key advantages of relational databases include the following:

 Categorizing data. Database administrators can easily categorize and store data in a relational
database that can then be queried and filtered to extract information for reports. Relational databases
are also easy to extend and aren't reliant on physical organization. After the original database creation,
a new data category can be added without having to modify the existing applications.

 Accuracy. Data is stored just once, eliminating data deduplication in storage procedures.

 Ease of use. Complex queries are easy for users to carry out with SQL, the main query language used
with relational databases.

 Collaboration. Multiple users can access the same database.

 Security. Direct access to data in tables within an RDBMS can be limited to specific users.

What are the disadvantages of relational databases?


The disadvantages of relational databases include the following:

 Structure. Relational databases require a lot of structure and a certain level of planning because
columns must be defined and data needs to fit correctly into somewhat rigid categories. The structure
is good in some situations, but it creates issues related to the other drawbacks, such as maintenance
and lack of flexibility and scalability.

 Maintenance issues. Developers and other personnel responsible for the database must spend time
managing and optimizing the database as data gets added to it.

 Inflexibility. Relational databases are not ideal for handling large quantities of unstructured data. Data
that is largely qualitative, not easily defined or dynamic is not optimal for relational databases, because
as the data changes or evolves, the schema must evolve with it, which takes time.

 Lack of scalability. Relational databases do not horizontally scale well across physical storage
structures with multiple servers. It is difficult to handle relational databases across multiple servers
because as a data set gets larger and more distributed, the structure is disrupted, and the use of multiple
servers has effects on performance -- such as application response times -- and availability.

Examples of relational databases


Standard relational databases enable users to manage predefined data relationships across multiple
databases. Popular examples of standard relational databases include Microsoft SQL Server, Oracle
Database, MySQL and IBM DB2.
Cloud-based relational databases, or database as a service, are also widely used because they enable
companies to outsource database maintenance, patching and infrastructure support requirements. Cloud
relational databases include Amazon Relational Database Service, Google Cloud SQL, IBM DB2 on
Cloud, SQL Azure and Oracle Cloud.

What are the differences between relational databases, non-relational databases and NoSQL?
The most important difference between relational database systems and non-relational database systems
is that relational databases are normalized. That is, they store data in a tabular form, arranged in a table
with rows and columns. A non-relational database stores data as files.
ALL RIGHTS RESERVED TO SVTI 112
Other differences include the following:
 Use of primary keys. Relational database tables each have a primary key identifier. In a non-relational
database, data is normally stored in hierarchical or navigational form, without the use of primary keys.

 Data values relationships. Since data in a relational database is stored in tables, the relationship
between these data values is stored as well. Since a non-relational database stores data as files, there
is no relationship between the data values.

 Integrity constraints. In a relational database, the integrity constraints are any constraint that ensures
database integrity. They are defined for the purpose of atomicity, consistency, isolation and durability,
or ACID. Non-relational databases do not use integrity constraints.

 Structured vs. unstructured data. Relational databases work well for structured data that conforms
to a predefined data model and doesn't change much. Non-relational databases are better for
unstructured data, which doesn't conform to a predefined data model and can't be stored in an RDBMS.
Examples of unstructured data include text, emails, photos, videos and web pages.

Non-relational databases are also called NoSQL databases. The terms are used interchangeably, but there
are differences.

SQL is the query language that is used with relational databases. Relational databases and their
management systems almost always use SQL as their underlying query language. NoSQL, or not only
SQL, databases use SQL and other query languages. For example, the NoSQL database management
program MongoDB uses JSON-like documents to store and organize data. (Technically, it uses a variant
of JSON call BSON, or binary JSON.)

Referring to databases as non-relational vs. relational categorizes them based on their architecture, and
referring to them as SQL vs. NoSQL categorizes them based on the query language, whether it is solely
SQL or not only SQL. Often, a relational database can be referred to as a SQL database, as many of them
use SQL, and non-relational databases can be referred to as NoSQL databases. NoSQL and non-relational
databases work well with more fluid data models, such as in engineering parts and molecular modeling,
where the data is always changing.

ALL RIGHTS RESERVED TO SVTI 113


Both relational and non-relational database platforms have their drawbacks. NewSQL databases seek
to provide the benefits of both types, by offering the data integrity and application access control that
relational databases offer and the horizontal scalability that non-relational or NoSQL platforms provide.
Data Analysis
Data analysis is defined as a process of cleaning, transforming, and modeling data to discover useful
information for business decision-making. The purpose of Data Analysis is to extract useful information
from data and taking the decision based upon the data analysis.

A simple example of Data analysis is whenever we take any decision in our day-to-day life is by thinking
about what happened last time or what will happen by choosing that particular decision. This is nothing
but analyzing our past or future and making decisions based on it. For that, we gather memories of our
past or dreams of our future. So that is nothing but data analysis. Now same thing analyst does for business
purposes, is called Data Analysis.

To grow your business even to grow in your life, sometimes all you need to do is Analysis!
If your business is not growing, then you have to look back and acknowledge your mistakes and make a
plan again without repeating those mistakes. And even if your business is growing, then you have to look
forward to making the business to grow more. All you need to do is analyze your business data and
business processes.
Data Analysis Tools

Data analysis tools make it easier for users to process and manipulate data, analyze the relationships and
correlations between data sets, and it also helps to identify patterns and trends for interpretation. Here is a
complete list of tools used for data analysis in research.
Types of Data Analysis: Techniques and Methods
There are several types of Data Analysis techniques that exist based on business and technology.
However, the major Data Analysis methods are:
 Text Analysis
 Statistical Analysis
 Diagnostic Analysis
 Predictive Analysis
 Prescriptive Analysis

Text Analysis
Text Analysis is also referred to as Data Mining. It is one of the methods of data analysis to discover a
pattern in large data sets using databases or data mining tools. It used to transform raw data into business
information. Business Intelligence tools are present in the market which is used to take strategic business
decisions. Overall it offers a way to extract and examine data and deriving patterns and finally
interpretation of the data.

ALL RIGHTS RESERVED TO SVTI 114


Statistical Analysis
Statistical Analysis shows "What happen?" by using past data in the form of dashboards. Statistical
Analysis includes collection, Analysis, interpretation, presentation, and modeling of data. It analyses a set
of data or a sample of data. There are two categories of this type of Analysis - Descriptive Analysis and
Inferential Analysis.
Descriptive Analysis
analyses complete data or a sample of summarized numerical data. It shows mean and deviation for
continuous data whereas percentage and frequency for categorical data.
Inferential Analysis
analyses sample from complete data. In this type of Analysis, you can find different conclusions from the
same data by selecting different samples.
Diagnostic Analysis
Diagnostic Analysis shows "Why did it happen?" by finding the cause from the insight found in Statistical
Analysis. This Analysis is useful to identify behavior patterns of data. If a new problem arrives in your
business process, then you can look into this Analysis to find similar patterns of that problem. And it may
have chances to use similar prescriptions for the new problems.

Predictive Analysis
Predictive Analysis shows "what is likely to happen" by using previous data. The simplest data analysis
example is like if last year I bought two dresses based on my savings and if this year my salary is increasing
double then I can buy four dresses. But of course it's not easy like this because you have to think about
other circumstances like chances of prices of clothes is increased this year or maybe instead of dresses
you want to buy a new bike, or you need to buy a house!
So here, this Analysis makes predictions about future outcomes based on current or past data. Forecasting
is just an estimate. Its accuracy is based on how much detailed information you have and how much you
dig in it.

Prescriptive Analysis
Prescriptive Analysis combines the insight from all previous Analysis to determine which action to take
in a current problem or decision. Most data-driven companies are utilizing Prescriptive Analysis because
predictive and descriptive Analysis are not enough to improve data performance. Based on current
situations and problems, they analyze the data and make decisions.

Data Analysis Process


The Data Analysis Process is nothing but gathering information by using a proper application or tool
which allows you to explore the data and find a pattern in it. Based on that information and data, you can
make decisions, or you can get ultimate conclusions.

Data Analysis consists of the following phases:


 Data Requirement Gathering
 Data Collection
 Data Cleaning
 Data Analysis
 Data Interpretation
 Data Visualization

Data Requirement Gathering


First of all, you have to think about why do you want to do this data analysis? All you need to find out the
purpose or aim of doing the Analysis of data. You have to decide which type of data analysis you wanted

ALL RIGHTS RESERVED TO SVTI 115


to do! In this phase, you have to decide what to analyze and how to measure it, you have to understand
why you are investigating and what measures you have to use to do this Analysis.

Data Collection
After requirement gathering, you will get a clear idea about what things you have to measure and what
should be your findings. Now it's time to collect your data based on requirements. Once you collect your
data, remember that the collected data must be processed or organized for Analysis. As you collected data
from various sources, you must have to keep a log with a collection date and source of the data.

Data Cleaning
Now whatever data is collected may not be useful or irrelevant to your aim of Analysis, hence it should
be cleaned. The data which is collected may contain duplicate records, white spaces or errors. The data
should be cleaned and error free. This phase must be done before Analysis because based on data cleaning,
your output of Analysis will be closer to your expected outcome.

Data Analysis
Once the data is collected, cleaned, and processed, it is ready for Analysis. As you manipulate data, you
may find you have the exact information you need, or you might need to collect more data. During this
phase, you can use data analysis tools and software which will help you to understand, interpret, and derive
conclusions based on the requirements.

Data Interpretation
After analyzing your data, it's finally time to interpret your results. You can choose the way to express or
communicate your data analysis either you can use simply in words or maybe a table or chart. Then use
the results of your data analysis process to decide your best course of action.

Data Visualization
Data visualization is very common in your day to day life; they often appear in the form of charts and
graphs. In other words, data shown graphically so that it will be easier for the human brain to understand
and process it. Data visualization often used to discover unknown facts and trends. By observing
relationships and comparing datasets, you can find a way to find out meaningful information.

Summary:

 Data analysis means a process of cleaning, transforming and modeling data to discover useful
information for business decision-making

 Types of Data Analysis are Text, Statistical, Diagnostic, Predictive, Prescriptive Analysis

 Data Analysis consists of Data Requirement Gathering, Data Collection, Data Cleaning, Data
Analysis, Data Interpretation, Data Visualization

Database languages in SQL Server


DDL, DML, DCL & TCL commands in SQL with syntax & examples
 DDL is Data Definition Language
 DML is Data Manipulation Language
 DCL is Data Control Language
 TCL is Transaction Control Language

ALL RIGHTS RESERVED TO SVTI 116


As you see from its name it allows to define, manipulate and control data and transactions in SQL
language.
It’s four types of SQL sub-languages, that’s why it’s no sense to search for a difference between DDL vs
DML or DCL vs TCL.
SQL commands list:

Language Command List

DDL CREATE
DROP
ALTER
RENAME
TRUNCATE

DML SELECT
INSERT
UPDATE
DELETE

DCL GRANT
REVOKE

TCL START TRANSACTION


COMMIT
ROLLBACK

DDL in SQL
DDL allows you to create SQL statements to make operations with database data structures (schemas,
tables etc.).

These are SQL DDL commands list and examples:


CREATE
CREATE statement is used to create a new database, table, index or stored procedure.

Create database example:


CREATE DATABASE explainjava;

Create table example:


CREATE TABLE user (
id INT(16) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL
);

DROP
DROP statement allows you to remove database, table, index or stored procedure.
Drop database example:
DROP DATABASE explainjava;
ALL RIGHTS RESERVED TO SVTI 117
Drop table example:
DROP TABLE user;

ALTER
ALTER is used to modify existing database data structures (database, table).
Alter table example:
ALTER TABLE user ADD COLUMN lastname VARCHAR(255) NOT NULL;

RENAME
RENAME command is used to rename SQL table.
Rename table example:
RENAME TABLE user TO student;

TRUNCATE
TRUNCATE operation is used to delete all table records.
Logically it’s the same as DELETE command.

Differences between DELETE and TRUNCATE commands are:

 TRUNCATE is really faster


 TRUNCATE cannot be rolled back
 TRUNCATE command does not invoke ON DELETE triggers

DML in SQL
DML is a Data Manipulation Language, it’s used to build SQL queries to manipulate (select, insert, update,
delete etc.) data in the database.
This is DML commands list with examples:

SELECT
SELECT query is used to retrieve a data from SQL tables.
Example:
SELECT * FROM student;

INSERT
INSERT command is used to add new rows into the database table.
Example:
INSERT INTO student (name, lastname) VALUES ('Dmytro', 'Shvechikov');

UPDATE
UPDATE statement modifies records into the table.
Example:
UPDATE student SET name = 'Dima' WHERE lastname = 'Shvechikov';

DELETE
DELETE query removes entries from the table.
Example:
DELETE FROM student WHERE name = 'Dima';

ALL RIGHTS RESERVED TO SVTI 118


DCL in SQL
DCL a Data Control Language.
Its commands are responsible for access restrictions inside of the database.
Let’s take a look at DCL statements definitions.

GRANT
GRANT command gives permissions to SQL user account.
For example, I want to grant all privileges to ‘explainjava’ database for user ‘dmytro@localhost’.
Let’s create a user first:
CREATE USER 'dmytro'@'localhost' IDENTIFIED BY '123';
Then I can grant all privileges using GRANT statement:
GRANT ALL PRIVILEGES ON explainjava.* TO 'dmytro'@'localhost';
and we have to save changes using FLUSH command:
FLUSH PRIVILEGES;

REVOKE
REVOKE statement is used to remove privileges from user accounts.
Example:
REVOKE ALL PRIVILEGES ON explainjava.* FROM 'dmytro'@'localhost';
and save changes:
FLUSH PRIVILEGES;

TCL in SQL
TCL is a Transaction Control Language.
Its commands are used to manage transactions in SQL databases.
This is TCL commands list:
START TRANSACTION (BEGIN, BEGIN WORK)
START TRANSACTION is used to start a new SQL transaction.
BEGIN and BEGIN WORK are aliases for START TRANSACTION.
Example:
START TRANSACTION;
after that, you’re doing manipulations with a data (insert, update, delete) and at the end, you need to
commit a transaction.

COMMIT
As a mentioned above COMMIT command finishes transaction and stores all changes made inside of a
transaction.
Example:
START TRANSACTION;
INSERT INTO student (name, lastname) VALUES ('Dmytro', 'Shvechikov');
COMMIT;

ROLLBACK
ROLLBACK statement reverts all changes made in the scope of transaction.
Example:
START TRANSACTION;
INSERT INTO student (name, lastname) VALUES ('Dmytro', 'Shvechikov');
ROLLBACK;

ALL RIGHTS RESERVED TO SVTI 119


CHAPTER 19

DATA MODELING
Data modeling
Data modeling is the process of creating a visual representation of either a whole information system or
parts of it to communicate connections between data points and structures. The goal is to illustrate the
types of data used and stored within the system, the relationships among these data types, the ways the
data can be grouped and organized and its formats and attributes.
Data models are built around business needs. Rules and requirements are defined upfront through feedback
from business stakeholders so they can be incorporated into the design of a new system or adapted in the
iteration of an existing one.
Data can be modeled at various levels of abstraction. The process begins by collecting information about
business requirements from stakeholders and end users. These business rules are then translated into data
structures to formulate a concrete database design. A data model can be compared to a roadmap, an
architect’s blueprint or any formal diagram that facilitates a deeper understanding of what is being
designed.
Data modeling employs standardized schemas and formal techniques. This provides a common,
consistent, and predictable way of defining and managing data resources across an organization, or even
beyond.
Ideally, data models are living documents that evolve along with changing business needs. They play an
important role in supporting business processes and planning IT architecture and strategy. Data models
can be shared with vendors, partners, and/or industry peers.
Types of data models
Like any design process, database and information system design begins at a high level of abstraction and
becomes increasingly more concrete and specific. Data models can generally be divided into three
categories, which vary according to their degree of abstraction. The process will start with a conceptual
model, progress to a logical model and conclude with a physical model. Each type of data model is
discussed in more detail below:
 Conceptual data models. They are also referred to as domain models and offer a big-picture view
of what the system will contain, how it will be organized, and which business rules are involved.
Conceptual models are usually created as part of the process of gathering initial project require-
ments. Typically, they include entity classes (defining the types of things that are important for the
business to represent in the data model), their characteristics and constraints, the relationships be-
tween them and relevant security and data integrity requirements. Any notation is typically simple.

ALL RIGHTS RESERVED TO SVTI 120


 Logical data models. They are less abstract and provide greater detail about the concepts and rela-
tionships in the domain under consideration. One of several formal data modeling notation systems
is followed. These indicate data attributes, such as data types and their corresponding lengths, and
show the relationships among entities. Logical data models don’t specify any technical system re-
quirements. This stage is frequently omitted in agile or DevOps practices. Logical data models can
be useful in highly procedural implementation environments, or for projects that are data-oriented
by nature, such as data warehouse design or reporting system development.

 Physical data models. They provide a schema for how the data will be physically stored within a
database. As such, they’re the least abstract of all. They offer a finalized design that can be imple-
mented as a relational database, including associative tables that illustrate the relationships among
entities as well as the primary keys and foreign keys that will be used to maintain those relationships.
Physical data models can include database management system (DBMS)-specific properties, includ-
ing performance tuning.

ALL RIGHTS RESERVED TO SVTI 121


Data modeling process
As a discipline, data modeling invites stakeholders to evaluate data processing and storage in painstaking
detail. Data modeling techniques have different conventions that dictate which symbols are used to
represent the data, how models are laid out, and how business requirements are conveyed. All approaches
provide formalized workflows that include a sequence of tasks to be performed in an iterative manner.
Those workflows generally look like this:
1. Identify the entities. The process of data modeling begins with the identification of the things,
events or concepts that are represented in the data set that is to be modeled. Each entity should be
cohesive and logically discrete from all others.
2. Identify key properties of each entity. Each entity type can be differentiated from all others be-
cause it has one or more unique properties, called attributes. For instance, an entity called “customer”
might possess such attributes as a first name, last name, telephone number and salutation, while an
entity called “address” might include a street name and number, a city, state, country and zip code.
3. Identify relationships among entities. The earliest draft of a data model will specify the nature of
the relationships each entity has with the others. In the above example, each customer “lives at” an
address. If that model were expanded to include an entity called “orders,” each order would be
shipped to and billed to an address as well. These relationships are usually documented via unified
modeling language (UML).
4. Map attributes to entities completely. This will ensure the model reflects how the business will
use the data. Several formal data modeling patterns are in widespread use. Object-oriented develop-
ers often apply analysis patterns or design patterns, while stakeholders from other business domains
may turn to other patterns.
5. Assign keys as needed, and decide on a degree of normalization that balances the need to re-
duce redundancy with performance requirements. Normalization is a technique for organizing
data models (and the databases they represent) in which numerical identifiers, called keys, are as-
signed to groups of data to represent relationships between them without repeating the data. For
instance, if customers are each assigned a key, that key can be linked to both their address and their
order history without having to repeat this information in the table of customer names. Normaliza-
tion tends to reduce the amount of storage space a database will require, but it can at cost to query
performance.
6. Finalize and validate the data model. Data modeling is an iterative process that should be repeated
and refined as business needs change.

Types of data modeling


Data modeling has evolved alongside database management systems, with model types increasing in
complexity as businesses' data storage needs have grown. Here are several model types:
 Hierarchical data models represent one-to-many relationships in a treelike format. In this type of
model, each record has a single root or parent which maps to one or more child tables. This model
was implemented in the IBM Information Management System (IMS), which was introduced in
1966 and rapidly found widespread use, especially in banking. Though this approach is less efficient
than more recently developed database models, it’s still used in Extensible Markup Language
(XML) systems and geographic information systems (GISs).
 Relational data models were initially proposed by IBM researcher E.F. Codd in 1970. They are
still implemented today in the many different relational databases commonly used in enterprise com-
puting. Relational data modeling doesn’t require a detailed understanding of the physical properties
of the data storage being used. In it, data segments are explicitly joined through the use of tables,
reducing database complexity.

ALL RIGHTS RESERVED TO SVTI 122


Relational databases frequently employ structured query language (SQL) for data management. These
databases work well for maintaining data integrity and minimizing redundancy. They’re often used in
point-of-sale systems, as well as for other types of transaction processing.
 Entity-relationship (ER) data models use formal diagrams to represent the relationships between
entities in a database. Several ER modeling tools are used by data architects to create visual maps
that convey database design objectives.
 Object-oriented data models gained traction as object-oriented programming and it became popu-
lar in the mid-1990s. The “objects” involved are abstractions of real-world entities. Objects are
grouped in class hierarchies, and have associated features. Object-oriented databases can incorporate
tables, but can also support more complex data relationships. This approach is employed in multi-
media and hypertext databases as well as other use cases.
 Dimensional data models were developed by Ralph Kimball, and they were designed to optimize
data retrieval speeds for analytic purposes in a data warehouse. While relational and ER models
emphasize efficient storage, dimensional models increase redundancy in order to make it easier to
locate information for reporting and retrieval. This modeling is typically used across OLAP systems.

Two popular dimensional data models are the star schema, in which data is organized into facts
(measurable items) and dimensions (reference information), where each fact is surrounded by its
associated dimensions in a star-like pattern. The other is the snowflake schema, which resembles the star
schema but includes additional layers of associated dimensions, making the branching pattern more
complex.
Benefits of data modeling
Data modeling makes it easier for developers, data architects, business analysts, and other stakeholders to
view and understand relationships among the data in a database or data warehouse. In addition, it can:
 Reduce errors in software and database development.
 Increase consistency in documentation and system design across the enterprise.
 Improve application and database performance.
 Ease data mapping throughout the organization.
 Improve communication between developers and business intelligence teams.
 Ease and speed the process of database design at the conceptual, logical and physical levels.

Data modeling tools


Numerous commercial and open source computer-aided software engineering (CASE) solutions are
widely used today, including multiple data modeling, diagramming and visualization tools. Here are
several examples:

 erwin Data Modeler is a data modeling tool based on the Integration DEFinition for information
modeling (IDEF1X) data modeling language that now supports other notation methodologies, in-
cluding a dimensional approach.

 Enterprise Architect is a visual modeling and design tool that supports the modeling of enterprise
information systems and architectures as well as software applications and databases. It’s based on
object-oriented languages and standards.

 ER/Studio is database design software that’s compatible with several of today’s most popular data-
base management systems. It supports both relational and dimensional data modeling.

 Free data modeling tools include open source solutions such as Open ModelSph

ALL RIGHTS RESERVED TO SVTI 123


ANSI-SPARC Architecture
The ANSI-SPARC Architecture, where ANSI-SPARC stands for American National Standards Institute,
Standards Planning And Requirements Committee, is an abstract design standard for a Database
Management System (DBMS), first proposed in 1975.[1]
The ANSI-SPARC model however never became a formal standard. No mainstream DBMS systems are
fully based on it (they tend not to exhibit full physical independence or to prevent direct user access to the
conceptual level), but the idea of logical data independence is widely adopted.

Three-level architecture
The objectives of the three-level architecture is to separate the user's view,
 It allows independent customized user views: Each user should be able to access the same data, but
have a different customized view of the data. These should be independent: changes to one view should
not affect others.
 It hides the physical storage details from users: Users should not have to deal with physical database
storage details.
 The database administrator should be able to change the database storage structures without affecting
the users’ views.
 The internal structure of the database should be unaffected by changes to the physical aspects of the
storage: For example, a changeover to a new disk.

The three levels are:


 External Level (User Views): A user's view of the database describes a part of the database that is
relevant to a particular user. It excludes irrelevant data as well as data which the user is not authorised
to access.
 Conceptual Level: The conceptual level is a way of describing what data is stored within the whole
database and how the data is inter-related. The conceptual level does not specify how the data is phys-
ically stored. Some important facts about this level are:
1. DBA works at this level.
2. Describes the structure of all users.
3. Only DBA can define this level.
4. Global view of database.
5. Independent of hardware and software.
 Internal Level: The internal level involves how the database is physically represented on the computer
system. It describes how the data is actually stored in the database and on the computer hardware.

ALL RIGHTS RESERVED TO SVTI 124


The Three Level Architecture has the aim of enabling users to access the same data but with a personalised
view of it. The distancing of the internal level from the external level means that users do not need to
know how the data is physically stored in the database. This level separation also allows the Database
Administrator (DBA) to change the database storage structures without affecting the users' views.
Database schemas
There are three different types of schema corresponding to the three levels in the ANSI-SPARC
architecture:
 The external schemas describe the different external views of the data and there may be many external
schemas for a given database.
 The conceptual schema describes all the data items and relationships between them, together with
integrity constraints (later). There is only one conceptual schema per database.
 The internal schema at the lowest level contains definitions of the stored records, the methods of
representation, the data fields, and indexes. There is only one internal schema per database.

The Entity Relationship Data Model


The entity relationship (ER) data model has existed for over 35 years. It is well suited to data modelling
for use with databases because it is fairly abstract and is easy to discuss and explain. ER models are readily
translated to relations. ER models, also called an ER schema, are represented by ER diagrams.
ER modelling is based on two concepts:
 Entities, defined as tables that hold specific information (data)
 Relationships, defined as the associations or interactions between entities

Here is an example of how these two concepts might be combined in an ER data model: Prof. Ba
(entity) teaches (relationship) the Database Systems course (entity).
For the rest of this chapter, we will use a sample database called the COMPANY database to illustrate the
concepts of the ER model. This database contains information about employees, departments and projects.

Important points to note include:


 There are several departments in the company. Each department has a unique identification, a name,
location of the office and a particular employee who manages the department.
 A department controls a number of projects, each of which has a unique name, a unique number and
a budget.
 Each employee has a name, identification number, address, salary and birthdate. An employee is as-
signed to one department but can join in several projects. We need to record the start date of the
employee in each project. We also need to know the direct supervisor of each employee.
 We want to keep track of the dependents for each employee. Each dependent has a name, birthdate
and relationship with the employee.

Entity, Entity Set and Entity Type


An entity is an object in the real world with an independent existence that can be differentiated from other
objects. An entity might be
 An object with physical existence (e.g., a lecturer, a student, a car)
 An object with conceptual existence (e.g., a course, a job, a position)

Entities can be classified based on their strength. An entity is considered weak if its tables are existence
dependent.
 That is, it cannot exist without a relationship with another entity
 Its primary key is derived from the primary key of the parent entity

ALL RIGHTS RESERVED TO SVTI 125


 The Spouse table, in the COMPANY database, is a weak entity because its primary key is dependent
on the Employee table. Without a corresponding employee record, the spouse record would not exist.

An entity is considered strong if it can exist apart from all of its related entities.
 Kernels are strong entities.
 A table without a foreign key or a table that contains a foreign key that can contain nulls is a strong
entity

Another term to know is entity type which defines a collection of similar entities.
An entity set is a collection of entities of an entity type at a particular point of time. In an entity relationship
diagram (ERD), an entity type is represented by a name in a box. For example, in Figure, the entity type
is EMPLOYEE.

.
Existence dependency
An entity’s existence is dependent on the existence of the related entity. It is existence-dependent if it has
a mandatory foreign key (i.e., a foreign key attribute that cannot be null). For example, in the COMPANY
database, a Spouse entity is existence -dependent on the Employee entity.

Kinds of Entities
You should also be familiar with different kinds of entities including independent entities, dependent
entities and characteristic entities. These are described below.

Independent entities
Independent entities, also referred to as kernels, are the backbone of the database. They are what other
tables are based on. Kernels have the following characteristics:
 They are the building blocks of a database.
 The primary key may be simple or composite.
 The primary key is not a foreign key.
 They do not depend on another entity for their existence.

If we refer back to our COMPANY database, examples of an independent entity include the Customer
table, Employee table or Product table.

Dependent entities
Dependent entities, also referred to as derived entities, depend on other tables for their meaning. These
entities have the following characteristics:
 Dependent entities are used to connect two kernels together.
 They are said to be existence dependent on two or more tables.
 Many to many relationships become associative tables with at least two foreign keys.
 They may contain other attributes.
 The foreign key identifies each associated table.
 There are three options for the primary key:
1. Use a composite of foreign keys of associated tables if unique
2. Use a composite of foreign keys and a qualifying column

ALL RIGHTS RESERVED TO SVTI 126


3. Create a new simple primary key

Characteristic entities
Characteristic entities provide more information about another table. These entities have the following
characteristics:
 They represent multivalued attributes.
 They describe other entities.
 They typically have a one to many relationship.
 The foreign key is used to further identify the characterized table.
 Options for primary key are as follows:
1. Use a composite of foreign key plus a qualifying column
2. Create a new simple primary key. In the COMPANY database, these might include:
 Employee (EID, Name, Address, Age, Salary) – EID is the simple primary key.
 EmployeePhone (EID, Phone) – EID is part of a composite primary key. Here, EID
is also a foreign key.

Attributes
Each entity is described by a set of attributes (e.g., Employee = (Name, Address, Birthdate (Age), Salary).
Each attribute has a name, and is associated with an entity and a domain of legal values. However, the
information about attribute domain is not presented on the ERD.
In the entity relationship diagram, shown in Figure, each attribute is represented by an oval with a name
inside.

Types of Attributes
There are a few types of attributes you need to be familiar with. Some of these are to be left as is, but some
need to be adjusted to facilitate representation in the relational model. This first section will discuss the
types of attributes. Later on we will discuss fixing the attributes to fit correctly into the relational model.

Simple attributes
Simple attributes are those drawn from the atomic value domains; they are also called single-valued
attributes. In the COMPANY database, an example of this would be: Name = {John} ; Age = {23}

Composite attributes
Composite attributes are those that consist of a hierarchy of attributes. Using our database example, and
shown in Figure, Address may consist of Number, Street and Suburb. So this would be written as →
Address = {59 + ‘Meek Street’ + ‘Kingsford’}

ALL RIGHTS RESERVED TO SVTI 127


Multivalued attributes
Multivalued attributes are attributes that have a set of values for each entity. An example of a multivalued
attribute from the COMPANY database, as seen in Figure, are the degrees of an employee: BSc, MIT,
PhD.

Derived attributes
Derived attributes are attributes that contain values calculated from other attributes. An example of this
can be seen in Figure. Age can be derived from the attribute Birthdate. In this situation, Birthdate is called
a stored attribute, which is physically saved to the database.

Keys
An important constraint on an entity is the key. The key is an attribute or a group of attributes whose values
can be used to uniquely identify an individual entity in an entity set.

Types of Keys
There are several types of keys. These are described below.

ALL RIGHTS RESERVED TO SVTI 128


Candidate key
A candidate key is a simple or composite key that is unique and minimal. It is unique because no two
rows in a table may have the same value at any time. It is minimal because every column is necessary in
order to attain uniqueness.

From our COMPANY database example, if the entity is Employee(EID, First Name, Last Name, SIN,
Address, Phone, BirthDate, Salary, DepartmentID), possible candidate keys are:
 EID, SIN
 First Name and Last Name – assuming there is no one else in the company with the same name
 Last Name and DepartmentID – assuming two people with the same last name don’t work in the
same department

Composite key
A composite key is composed of two or more attributes, but it must be minimal.
Using the example from the candidate key section, possible composite keys are:
 First Name and Last Name – assuming there is no one else in the company with the same name
 Last Name and Department ID – assuming two people with the same last name don’t work in the
same department

Primary key
The primary key is a candidate key that is selected by the database designer to be used as an identifying
mechanism for the whole entity set. It must uniquely identify tuples in a table and not be null. The primary
key is indicated in the ER model by underlining the attribute.
 A candidate key is selected by the designer to uniquely identify tuples in a table. It must not be null.
 A key is chosen by the database designer to be used as an identifying mechanism for the whole entity
set. This is referred to as the primary key. This key is indicated by underlining the attribute in the ER
model.

In the following example, EID is the primary key:


Employee(EID, First Name, Last Name, SIN, Address, Phone, BirthDate, Salary, DepartmentID)

Secondary key
A secondary key is an attribute used strictly for retrieval purposes (can be composite), for example: Phone
and Last Name.

Alternate key
Alternate keys are all candidate keys not chosen as the primary key.

Foreign key
A foreign key (FK) is an attribute in a table that references the primary key in another table OR it can be
null. Both foreign and primary keys must be of the same data type.
In the COMPANY database example below, DepartmentID is the foreign key:
Employee(EID, First Name, Last Name, SIN, Address, Phone, BirthDate, Salary, DepartmentID)

Nulls
A null is a special symbol, independent of data type, which means either unknown or inapplicable. It does
not mean zero or blank. Features of null include:
 No data entry
 Not permitted in the primary key
 Should be avoided in other attributes
 Can represent

ALL RIGHTS RESERVED TO SVTI 129


o An unknown attribute value
o A known, but missing, attribute value
o A “not applicable” condition
 Can create problems when functions such as COUNT, AVERAGE and SUM are used
 Can create logical problems when relational tables are linked

NOTE: The result of a comparison operation is null when either argument is null. The result of an
arithmetic operation is null when either argument is null (except functions that ignore nulls).

Example of how null can be used


Use the Salary table (Salary_tbl) in Figure to follow an example of how null can be used.

To begin, find all employees (emp#) in Sales (under the jobName column) whose salary plus commission
are greater than 30,000.
 SELECT emp# FROM Salary_tbl
 WHERE jobName = Sales AND
 (commission + salary) > 30,000 –> E10 and E12

This result does not include E13 because of the null value in the commission column. To ensure that the
row with the null value is included, we need to look at the individual fields. By adding commission and
salary for employee E13, the result will be a null value. The solution is shown below.
 SELECT emp# FROM Salary_tbl
 WHERE jobName = Sales AND
 (commission > 30000 OR
 salary > 30000 OR
 (commission + salary) > 30,000 –>E10 and E12 and E13

Relationships
Relationships are the glue that holds the tables together. They are used to connect related information
between tables.
Relationship strength is based on how the primary key of a related entity is defined. A weak, or non-
identifying, relationship exists if the primary key of the related entity does not contain a primary key
component of the parent entity. Company database examples include:
 Customer(CustID, CustName)
 Order(OrderID, CustID, Date)

A strong, or identifying, relationship exists when the primary key of the related entity contains the primary
key component of the parent entity. Examples include:
 Course(CrsCode, DeptCode, Description)
 Class(CrsCode, Section, ClassTime…)

Types of Relationships
ALL RIGHTS RESERVED TO SVTI 130
Below are descriptions of the various types of relationships.

One to many (1:M) relationship


A one to many (1:M) relationship should be the norm in any relational database design and is found in all
relational database environments. For example, one department has many employees. Figure shows the
relationship of one of these employees to the department.

One to one (1:1) relationship


A one to one (1:1) relationship is the relationship of one entity to only one other entity, and vice versa. It
should be rare in any relational database design. In fact, it could indicate that two entities actually belong
in the same table.
An example from the COMPANY database is one employee is associated with one spouse, and one spouse
is associated with one employee.

Many to many (M:N) relationships


For a many to many relationship, consider the following points:
 It cannot be implemented as such in the relational model.
 It can be changed into two 1:M relationships.
 It can be implemented by breaking up to produce a set of 1:M relationships.
 It involves the implementation of a composite entity.
 Creates two or more 1:M relationships.
 The composite entity table must contain at least the primary keys of the original tables.
 The linking table contains multiple occurrences of the foreign key values.
 Additional attributes may be assigned as needed.
 It can avoid problems inherent in an M:N relationship by creating a composite entity or bridge
entity. For example, an employee can work on many projects OR a project can have many em-
ployees working on it, depending on the business rules. Or, a student can have many classes and a
class can hold many students.

Figure shows another another aspect of the M:N relationship where an employee has different start dates
for different projects. Therefore, we need a JOIN table that contains the EID, Code and StartDate.

ALL RIGHTS RESERVED TO SVTI 131


Example of mapping an M:N binary relationship type
 For each M:N binary relationship, identify two relations.
 A and B represent two entity types participating in R.
 Create a new relation S to represent R.
 S needs to contain the PKs of A and B. These together can be the PK in the S table OR these together
with another simple attribute in the new table R can be the PK.
 The combination of the primary keys (A and B) will make the primary key of S.

Unary relationship (recursive)


A unary relationship, also called recursive, is one in which a relationship exists between occurrences of
the same entity set. In this relationship, the primary and foreign keys are the same, but they represent two
entities with different roles. For some entities in a unary relationship, a separate column can be created
that refers to the primary key of the same entity set.

Ternary Relationships
A ternary relationship is a relationship type that involves many to many relationships between three
tables.
Refer to Figure for an example of mapping a ternary relationship type. Note n-ary means multiple tables
in a relationship. (Remember, N = many.)
 For each n-ary (> 2) relationship, create a new relation to represent the relationship.
 The primary key of the new relation is a combination of the primary keys of the participating entities
that hold the N (many) side.
 In most cases of an n-ary relationship, all the participating entities hold a many side.

ALL RIGHTS RESERVED TO SVTI 132


CHAPTER 20

NORMALIZATION
Normalization
Normalization is a database design technique that reduces data redundancy and eliminates undesirable
characteristics like Insertion, Update and Deletion Anomalies. Normalization rules divides larger tables
into smaller tables and links them using relationships. The purpose of Normalisation in SQL is to eliminate
redundant (repetitive) data and ensure data is stored logically.

The inventor of the relational model Edgar Codd proposed the theory of normalization of data with the
introduction of the First Normal Form, and he continued to extend theory with Second and Third Normal
Form. Later he joined Raymond F. Boyce to develop the theory of Boyce-Codd Normal Form.
Database Normal Forms
Here is a list of Normal Forms in SQL:
What is Database SQL
 1NF (First Normal Form)
 2NF (Second Normal Form)
 3NF (Third Normal Form)
 BCNF (Boyce-Codd Normal Form)
 4NF (Fourth Normal Form)
 5NF (Fifth Normal Form)
 6NF (Sixth Normal Form)

The Theory of Data Normalization in MySQL server is still being developed further. For example, there
are discussions even on 6th Normal Form. However, in most practical applications, normalization
achieves its best in 3rd Normal Form. The evolution of Normalization in SQL theories is illustrated
below-

Database Normal Forms


Database Normalization With Examples
Database Normalization Example can be easily understood with the help of a case study. Assume, a video
library maintains a database of movies rented out. Without any normalization in database, all information
is stored in one table as shown below. Let's understand Normalization database with normalization
example with solution:

ALL RIGHTS RESERVED TO SVTI 133


Here you see Movies Rented column has multiple values. Now let's move into 1st Normal Forms:
1NF (First Normal Form) Rules
 Each table cell should contain a single value.
 Each record needs to be unique.

The above table in 1NF-


1NF Example

Example of 1NF in DBMS

Before we proceed let's understand a few things --


What is a KEY in SQL?
A KEY in SQL is a value used to identify records in a table uniquely. An SQL KEY is a single column or
combination of multiple columns used to uniquely identify rows or tuples in the table. SQL Key is used
to identify duplicate information, and it also helps establish a relationship between multiple tables in the
database.
Note: Columns in a table that are NOT used to identify a record uniquely are called non-key columns.

What is a Primary Key?


Primary Key in DBMS
A primary is a single column value used to identify a database record uniquely.
It has following attributes
 A primary key cannot be NULL
 A primary key value must be unique
 The primary key values should rarely be changed
 The primary key must be given a value when a new record is inserted.

What is Composite Key?


A composite key is a primary key composed of multiple columns used to identify a record uniquely
In our database, we have two people with the same name Robert Phil, but they live in different places.

ALL RIGHTS RESERVED TO SVTI 134


Composite key in Database

Hence, we require both Full Name and Address to identify a record uniquely. That is a composite key.
Let's move into second normal form 2NF

2NF (Second Normal Form) Rules


 Rule 1- Be in 1NF
 Rule 2- Single Column Primary Key that does not functionally dependant on any subset of candi-
date key relation

It is clear that we can't move forward to make our simple database in 2nd Normalization form unless we
partition the table above.

We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains member
information. Table 2 contains information on movies rented.
We have introduced a new column called Membership_id which is the primary key for table 1. Records
can be uniquely identified in Table 1 using membership id

Database - Foreign Key


In Table 2, Membership_ID is the Foreign Key

Foreign Key in DBMS


Foreign Key references the primary key of another Table! It helps connect your Tables
 A foreign key can have a different name from its primary key
 It ensures rows in one table have corresponding rows in another
 Unlike the Primary key, they do not have to be unique. Most often they aren't
 Foreign keys can be null even though primary keys can not

ALL RIGHTS RESERVED TO SVTI 135


Why do you need a foreign key?
Suppose, a novice inserts a record in Table B such as

You will only be able to insert values into your foreign key that exist in the unique key in the parent table.
This helps in referential integrity.

The above problem can be overcome by declaring membership id from Table2 as foreign key of
membership id from Table1

Now, if somebody tries to insert a value in the membership id field that does not exist in the parent table,
an error will be shown!

What are transitive functional dependencies?

A transitive functional dependency is when changing a non-key column, might cause any of the other non-
key columns to change

ALL RIGHTS RESERVED TO SVTI 136


Consider the table 1. Changing the non-key column Full Name may change Salutation.

Let's move into 3NF

3NF (Third Normal Form) Rules


Rule 1- Be in 2NF
Rule 2- Has no transitive functional dependencies
To move our 2NF table into 3NF, we again need to again divide our table.

3NF Example
Below is a 3NF example in SQL database:

We have again divided our tables and created a new table which stores Salutations.

There are no transitive functional dependencies, and hence our table is in 3NF

In Table 3 Salutation ID is primary key, and in Table 1 Salutation ID is foreign to primary key in Table 3

Now our little example is at a level that cannot further be decomposed to attain higher normal form types
of normalization in DBMS. In fact, it is already in higher normalization forms. Separate efforts for moving
into next levels of normalizing data are normally needed in complex databases. However, we will be
discussing next levels of normalisation in DBMS in brief in the following.

BCNF (Boyce-Codd Normal Form)


Even when a database is in 3rd Normal Form, still there would be anomalies resulted if it has more than
one Candidate Key.
Sometimes is BCNF is also referred as 3.5 Normal Form.

4NF (Fourth Normal Form) Rules


If no database table instance contains two or more, independent and multivalued data describing the
relevant entity, then it is in 4th Normal Form.
5NF (Fifth Normal Form) Rules
A table is in 5th Normal Form only if it is in 4NF and it cannot be decomposed into any number of smaller
tables without loss of data.
ALL RIGHTS RESERVED TO SVTI 137
6NF (Sixth Normal Form) Proposed
6th Normal Form is not standardized, yet however, it is being discussed by database experts for some
time. Hopefully, we would have a clear & standardized definition for 6th Normal Form in the near future...
That's all to SQL Normalization!!!

Summary
 Database designing is critical to the successful implementation of a database management system
that meets the data requirements of an enterprise system.
 Normalization in DBMS is a process which helps produce database systems that are cost-effective
and have better security models.
 Functional dependencies are a very important component of the normalize data process
 Most database systems are normalized database up to the third normal forms in DBMS.
 A primary key uniquely identifies are record in a Table and cannot be null
 A foreign key helps connect table and references a primary key

Denormalization in Databases
Denormalization is a database optimization technique in which we add redundant data to one or more
tables. This can help us avoid costly joins in a relational database. Note that denormalization does not
mean not doing normalization. It is an optimization technique that is applied after doing normalization.
In a traditional normalized database, we store data in separate logical tables and attempt to minimize
redundant data. We may strive to have only one copy of each piece of data in database.
For example, in a normalized database, we might have a Courses table and a Teachers table. Each entry
in Courses would store the teacherID for a Course but not the teacherName. When we need to retrieve
a list of all Courses with the Teacher’s name, we would do a join between these two tables.
In some ways, this is great; if a teacher changes his or her name, we only have to update the name in
one place.
The drawback is that if tables are large, we may spend an unnecessarily long time doing joins on tables.
Denormalization, then, strikes a different compromise. Under denormalization, we decide that we’re
okay with some redundancy and some extra effort to update the database in order to get the efficiency
advantages of fewer joins.
Pros of Denormalization:-
1. Retrieving data is faster since we do fewer joins
2. Queries to retrieve can be simpler(and therefore less likely to have bugs),
since we need to look at fewer tables.

Cons of Denormalization:-
1. Updates and inserts are more expensive.
2. Denormalization can make update and insert code harder to write.
3. Data may be inconsistent . Which is the “correct” value for a piece of data?
4. Data redundancy necessitates more storage.

ALL RIGHTS RESERVED TO SVTI 138


CHAPTER 21

RELATIONSHIPS
Introduction to Database Relationships
The database terms relational and relationship describe the way that data in tables are connected. A
relational database consists of a series of two or more tables linked by a specific key. A relational
database differs from unstructured databases, which are common in big data initiatives. Relational
databases tend to require strict rules about how tables are defined and what constitutes a valid
relationship among tables.

Types of Database Relationships


Relationships allow you to describe the connections between database tables in powerful ways. These
relationships can then be leveraged to perform powerful cross-table queries, known as JOINs.
There are three types of database relationships, each named according to the number of table rows
involved in the relationship. Each of these three relationship types exists between two tables.

 One-to-one relationships occur when each entry in the first table has only one counterpart in the
second table. One-to-one relationships are rarely used because it is often more efficient to put all
the information in a single table. Some database designers take advantage of this relationship by
creating tables that contain a subset of the data from another table.

 One-to-many relationships are the most common type of database relationship. They occur when
each record in Table A corresponds to one or more records in Table B, but each record in Table B
corresponds to only one record in Table A. For example, the relationship between a Teachers table
and a Students table in an elementary school database would likely be a one-to-many relationship
because each student has only one teacher, but each teacher has several students. This one-to-many
design helps eliminate duplicated data.

 Many-to-many relationships occur when each record in Table A corresponds to one or more
records in Table B, and each record in Table B corresponds to one or more records in Table A. For
example, the relationship between a Teachers table and a Courses table would likely be many-to-
many because each teacher may instruct more than one course, and each course may have more
than one instructor.

Self-Referencing Relationships: A Special Case


Self-referencing relationships occur when there is only one table involved. One common example is an
Employees table that contains information about the supervisor of each employee. Each supervisor is also
an employee and has a supervisor. In this case, there is a one-to-many self-referencing relationship, as
each employee has one supervisor, but each supervisor may have more than one employee.

Creating Relationships With Foreign Keys


You create relationships between tables by specifying a foreign key. This key tells the relational database
how the tables are related. In many cases, a column in Table A contains primary keys that are referenced
from Table B.

Consider the example of the Teachers and Students tables. The Teachers table contains an ID, a name,
and a course column:

ALL RIGHTS RESERVED TO SVTI 139


InstructorID Teacher_Name Course

001 John Doe English

002 Jane Schmoe Math

The Students table includes an ID, name, and a foreign key column:
StudentID Student_Name Teacher_FK

0200 Lowell Smith 001


0201 Brian Short 001

0202 Corky Mendez 002

0203 Monica Jones 001

The column Teacher_FK in the Students table references the primary key value of an instructor in the
Teachers table. Frequently, database designers use PK or FK in the column name to identify a primary
key or foreign key column.
These two tables illustrate a one-to-many relationship between the teachers and the students.

Relationships and Referential Integrity


After adding a foreign key to a table, create a database constraint that enforces referential integrity be-
tween the two tables. This step ensures that relationships between tables remain consistent. When one
table has a foreign key to another table, referential integrity requires that any foreign key value in Table
B must refer to an existing record in Table A.

Implementing relationships
Depending on your database, you'll implement relationships between tables in different ways. Microsoft
Access provides a wizard that allows you to link tables and also enforce referential integrity.
If you are writing SQL directly, first create the table Teachers, declaring an ID column to be the primary
key:

CREATE TABLE Teachers (InstructorID INT AUTO_INCREMENT PRIMARY KEY,


Teacher_Name VARCHAR(100),
Course VARCHAR(100)
);

When you create the Students table, you declare the Teacher_FK column to be a foreign key referenc-
ing the InstructorID column in the Teachers' table:
CREATE TABLE Students (
StudentID INT AUTO_INCREMENT PRIMARY KEY,
Student_Name VARCHAR(100), Teacher_FK INT,
FOREIGN KEY (Teacher_FK) REFERENCES Teachers(InstructorID) )
);

ALL RIGHTS RESERVED TO SVTI 140


Using Relationships to Join Tables
After creating one or more relationships in your database, leverage their power by using SQL JOIN queries
to combine information from multiple tables. The most common type of join is a SQL INNER JOIN,
which is a simple join. This type of join returns all records that meet the join condition from one or more
tables.

For example, this JOIN condition returns Student_Name, Teacher_Name, and Course, where the foreign
key in the Students table matches the primary key in the Teachers table:

SELECT Students.Student_Name, Teachers.Teacher_Name, Teachers.Course


FROM Students
INNER JOIN Teachers
ON Students.Teacher_FK=Teachers.InstructorID;

This statement produces a table something like this:


Student_Name Teacher_Name Course
Lowell Smith John Doe English
Brian Short John Doe English
Corky Mendez Jane Schmoe Math
Monica Jones John Doe English

ALL RIGHTS RESERVED TO SVTI 141


CHAPTER 22

SQL PERFORMANCE
SQL - Indexes
Indexes are special lookup tables that the database search engine can use to speed up data retrieval.
Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index in
the back of a book.

For example, if you want to reference all pages in a book that discusses a certain topic, you first refer to
the index, which lists all the topics alphabetically and are then referred to one or more specific page
numbers.

An index helps to speed up SELECT queries and WHERE clauses, but it slows down data input, with
the UPDATE and the INSERT statements. Indexes can be created or dropped with no effect on the data.

Creating an index involves the CREATE INDEX statement, which allows you to name the index, to
specify the table and which column or columns to index, and to indicate whether the index is in an
ascending or descending order.

Indexes can also be unique, like the UNIQUE constraint, in that the index prevents duplicate entries in
the column or combination of columns on which there is an index.

The CREATE INDEX Command


The basic syntax of a CREATE INDEX is as follows.
CREATE INDEX index_name ON table_name;

Single-Column Indexes
A single-column index is created based on only one table column. The basic syntax is as follows.
CREATE INDEX index_name
ON table_name (column_name);

Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A unique index does not
allow any duplicate values to be inserted into the table. The basic syntax is as follows.
CREATE UNIQUE INDEX index_name
on table_name (column_name);

Composite Indexes
A composite index is an index on two or more columns of a table. Its basic syntax is as follows.
CREATE INDEX index_name
on table_name (column1, column2);
Whether to create a single-column index or a composite index, take into consideration the column(s) that
you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should there be two
or more columns that are frequently used in the WHERE clause as filters, the composite index would be
the best choice.

Implicit Indexes
Implicit indexes are indexes that are automatically created by the database server when an object is
created. Indexes are automatically created for primary key constraints and unique constraints.

ALL RIGHTS RESERVED TO SVTI 142


The DROP INDEX Command
An index can be dropped using SQL DROP command. Care should be taken when dropping an index
because the performance may either slow down or improve.

The basic syntax is as follows −

DROP INDEX index_name;


You can check the INDEX Constraint chapter to see some actual examples on Indexes.

When should indexes be avoided?


Although indexes are intended to enhance a database's performance, there are times when they should be
avoided.
The following guidelines indicate when the use of an index should be reconsidered.
 Indexes should not be used on small tables.
 Tables that have frequent, large batch updates or insert operations.
 Indexes should not be used on columns that contain a high number of NULL values.
 Columns that are frequently manipulated should not be indexed.

QUERY PERFORMANCE
The following guidelines can help you optimize the performance of a local Access database — a database
that is stored on a local hard disk drive, rather than on a network.
 Turn off Name AutoCorrect
 Set the database to compact and repair automatically
 Open the database in exclusive mode
 Turn off AutoCorrect options

Turn off Name AutoCorrect


The Name AutoCorrect feature helps ensure that the functionality of database objects remains intact when
other database objects that they depend upon are renamed. For example, if you rename a table and there
are queries that use that table, Name AutoCorrect makes sure that those queries do not break because of
the change. This feature can be useful, but it does slow performance some.
If your database design is stable and its objects will not be renamed, you can safely turn off Name
AutoCorrect to improve performance.
1. Open the database that you want to optimize.
2. Click File > Options to open the Access Options dialog box.
3. In the left pane of the Access Options dialog box, click Current Database.
4. In the right pane, under Name AutoCorrect Options, clear all the check boxes.

Set the database to compact and repair automatically


Over time, the performance of a database file can become slow because of space that remains allocated to
deleted or temporary objects. The Compact and Repair command removes this wasted space and can
help a database run faster and more efficiently. You can set an option to run the Compact and
Repair command automatically when a database closes.
1. Open the database that you want to optimize.
2. Click File > Options to open the Access Options dialog box.
3. In the left pane of the Access Options dialog box, click Current Database.
4. In the right pane, under Application Options, select the Compact on Close check box.

ALL RIGHTS RESERVED TO SVTI 143


Open the database in exclusive mode
If you are the only person using a database, opening the database in exclusive mode prevents other users
from using the database at the same time and can help improve performance.
 Start Access, but do not open a database. If you already have a database open, close it.
 Click Open and then click Browse.
 In the Open dialog box, select the database file that you want to open. You can use the Look in list if
you need to browse to find the database file.
 Click the arrow on the Open button, and then click Open Exclusive.

Turn off AutoCorrect options


By default, Access corrects your spelling as you type. You can turn off the AutoCorrect feature to help
improve performance.
 Open the database that you want to optimize.
 Click File > Options to open the Access Options dialog box.
 In the left pane of the Access Options dialog box, click Proofing.
 In the right pane, under AutoCorrect options, click AutoCorrect Options.
 In the AutoCorrect Options dialog box, clear the check boxes for the options that you don't want.

Note: You do not need to turn off all the AutoCorrect options to see a benefit, but the more AutoCorrect
options that you turn off, the bigger the benefit.

Help improve performance in a multiuser environment


The following guidelines can help you optimize the performance of an Access database that is used in a
multiuser environment.
 Split the database
 Change the page-level or record-level locking setting
 Choose an appropriate record-locking setting
 Adjust the network refresh and update settings

Split the database


When you split a database, you put the data tables in a database file on a network server in what is called
a back-end database. You put the other database objects, such as queries, forms, and reports, in another
database file that is called the front-end database. Users keep their own copy of the front-end database on
their computers. Performance will improve because only the data is sent across the network.
You split a database by using the Database Splitter Wizard.
 On the Database Tools tab, in the Move Data group, click Access Database.

Change the page-level or record-level locking setting


Access locks a certain amount of data while you edit records. The amount of data that is locked depends
on the locking setting that you choose. You can help improve performance by choosing page-level locking.
However, page-level locking may decrease data availability, because more data is locked than with record-
level locking.
 Page-level locking Access locks the page that contains the record (the page is the area of
memory where the record is located). Editing a record with page-level locking enabled might also
cause other records stored nearby in memory to be locked. However, performance is generally
faster when you use page-level locking instead of record-level locking.
 Record-level locking Access locks only the record that is being edited. Other records are not
affected.

ALL RIGHTS RESERVED TO SVTI 144


Change the page-level or record-level locking setting
 Open the database that you want to adjust.
 Click File > Options to open the Access Options dialog box.
 In the left pane, click Client Settings.
 In the right pane, in the Advanced section, select or clear the Open databases by using record-level
locking check box.

Choose an appropriate record-locking setting


Access locks records while you edit them. The number of records that Access locks and the amount of
time those records are locked depends on the record-locking setting that you choose.
No locks Access doesn't lock a record or page until a user saves changes to it, which results in data
being more readily available. However, data conflicts (simultaneous changes being made to the same
record) can occur if you use this setting. When a data conflict occurs, the user must decide which version
of the data to keep. This is generally the fastest option, but data conflicts may outweigh the performance
gain.
Edited record Access locks a record as soon as a user begins to edit it. As a result, records are locked
for longer periods of time, but data conflicts are less likely.
All records Access locks all the records in a table while any form or datasheet that uses that table is
open. This can improve performance for the user who is editing data in the table, but it restricts other
users' ability to edit data more than the other options do.

Change the record-locking setting


1. Open the database that you want to adjust.
2. Click File > Options to open the Access Options dialog box.
3. In the left pane, click Client Settings.
4. In the right pane, in the Advanced section, under Default record locking, click the option that you
want.

Adjust the network refresh and update settings


Try adjusting the Refresh interval (sec), Update retry interval (msec), Number of update retries,
and ODBC refresh interval (sec) settings, as applicable.
You use the Update retry interval and Number of update retries settings to specify how often and how
many times Access tries to save a record when it is locked by another user.
You use the ODBC refresh interval and Refresh interval settings to control how often Access refreshes
your data. Refreshing only updates data that already exists in your datasheet or form. Refreshing does not
reorder records, display new records, or remove deleted records and records from query results that no
longer meet specified criteria. To view such changes, you requery the underlying records for the datasheet
or form.

Change the network refresh and update settings


1. Open the database that you want to help run faster.
2. Click File > Options to open the Access Options dialog box.
3. In the left pane, click Client Settings.
4. In the right pane, in the Advanced section, change the settings that you want.

ALL RIGHTS RESERVED TO SVTI 145


Concurrency Control in SQL Server
A “Transaction” in SQL Server
The standard definition of a transaction states that “every query that runs in a SQL Server is in a
transaction,” that means any query you run on a SQL Server is considered as being in a transaction. It
could either be a simple SELECT query or any UPDATE or ALTER query.
 If you run a query without mentioning the BEGIN TRAN keyword then it would be considered an
implicit transition.
 If you run a query that starts with BEGIN TRAN and ends with COMMIT or ROLLBACK, then
it would be considered an explicit transaction.

Transaction Properties
A database management system (DBMS) is considered a relational database management system
(RDBMS) if it follows the transactional properties, ACID.
 A: Atomicity
 C: Consistency
 I: Isolation
 D: Durability

The SQL Server takes care of the Atomicity, Consistency, and Durability of the system, and the user has
to care about the Isolation property of the transaction. The meaning of each of these properties is described
below, as it applies to a transaction.
Atomicity
Transaction work should be atomic, which means all the work is one unit. If the user performs a transition,
either the transaction should complete and perform all the asked operations, or it should fail and don’t do
anything. Atomicity deals with the transaction process and an RDBMS transaction does not leave the work
incomplete.

Consistency
After the transaction is completed, the database should not be left in an inconsistent state, which means
the data on which transaction is applied must be logically correct, according to the rules of the system.

Isolation
If two transactions are applied on a similar database, then both the transaction should be isolated from
each other, and the user must see the result. It can also be defined as a transaction that should see the data
only after or before the concurrent transaction process is completed, which means if a one transaction
process is in between, the other transaction process should wait until the first transaction is completed.
For instance, if A performs a transaction process on data d1, and before the transaction process gets
completed, B also performs another transaction process on the same data d1. Here, the isolation property
will isolate the transaction process of A and B, and the transaction process of B will only start after the
transaction process of A gets completed.

Durability
Even if the system fails, the transaction should be persistent, which means, if the system fails during a
transaction process, the transaction should be dropped, too, without affecting the data.

Concurrency in SQL Server


Concurrency is a situation that arises in a database due to the transaction process. Concurrency occurs
when two or more than two users are trying to access the same data or information. DBMS concurrency
is considered a problem because accessing data simultaneously by two different users can lead to
inconsistent results or invalid behaviour.

ALL RIGHTS RESERVED TO SVTI 146


Concurrency Problem Types
The concurrency problem mostly arises when both the users try to write the same data, or when one is
writing and the other is reading. Apart from this logic, there are some common types of concurrency
problems:
 Dirty Reads
 Lost Updates
 Non-repeatable Reads
 Phantom Reads

Dirty Read
This problem occurs when another process reads the changed, but uncommitted data. For instance, if one
process has changed data but not committed it yet, another process is able to read the same data. This leads
to the inconsistent state for the reader.

Lost Updates
This problem occurs when two processes try to manipulate the same data simultaneously. This problem
can lead to data loss, or the second process might overwrite the first processs change.

Non-repeatable Reads
This problem occurs when one process is reading the data, and another process is writing the data. In non-
repeatable reads, the first process reading the value might get two different values, as the changed data is
read a second time because the second process changes the data.

Phantom Reads
If two same queries executed by two users show different output, then it would be a Phantom Read
problem. For instance, If user A select a query to read some data, at the same time the user B insert some
new data but the user A only get able to read the old data at the first attempt, but when user A re-query
the same statement then he/she gets a different set of data.

Solve Concurrency Problems


SQL Server provides 5 different levels of transaction isolation to overcome these Concurrency problems.
These 5 isolation levels work on two major concurrency models:
1. Pessimistic model - In the pessimistic model of managing concurrent data access, the readers can
block writers, and the writers can block readers.
2. Optimistic model - In the optimistic model of managing concurrent data access, the readers cannot
block writers, and the writers cannot block readers, but the writer can block another writer.

Note that readers are users are performing the SELECT operations. Writers are users are performing
INSERT, ALTER, UPDATE, S.E.T. operations.

Isolation Level
When we connect to a SQL server database, the application can submit queries to the database with one
of five different isolation levels. These levels are:
 Read Uncommitted
 Read Committed
 Repeatable Read
 Serializable
 Snapshot

ALL RIGHTS RESERVED TO SVTI 147


Out of these five isolation levels, Read Uncommitted, Read Committed, Repeatable Read, and Serializable
come under the pessimistic concurrency model. Snapshot comes under the optimistic concurrency model.
These levels are ordered in terms of the separation of work by two different processes, from minimal
separation to maximal.
Let's look at each of these isolation levels and how they affect concurrency of operations.

Read Uncommitted
This is the first level of isolation, and it comes under the pessimistic model of concurrency. In Read
Uncommitted, one transaction is allowed to read the data that is about to be changed by the commit of
another process. Read Uncommitted allows the dirty read problem.

Read Committed
This is the second level of isolation and also falls under the pessimistic model of concurrency. In the Read
Committed isolation level, we are only allowed to read data that is committed, which means this level
eliminates the dirty read problem. In this level, if you are reading data then the concurrent transactions
that can delete or write data, some work is blocked until other work is complete.

Repeatable Read
The Repeatable Read isolation level is similar to the Read Committed level and eliminates the Non-
Repeatable Read problem. In this level, the transaction has to wait till another transaction's update or read
query is complete. But if there is an insert transaction, it does not wait for anyone. This can lead to the
Phantom Read problem.

Serializable
This is the highest level of isolation in the pessimistic model. By implementing this level of isolation, we
can prevent the Phantom Read problem. In this level of isolation, we can ask any transaction to wait until
the current transaction completes.

Snapshot
Snapshot follows the optimistic model of concurrency, and this level of isolation takes a snapshot of the
current data and uses it as a copy for the different transactions. Here each transaction has its copy of data,
so if a user tries to perform a transaction like an update or insert, it asks him to re-verify all the operation
before the process gets started executing.

Conclusion
Concurrency occurs when two transactions operate currently on the same set of data. Concurrency can
then lead to data inconsistency and abnormal behaviour for a transaction. RDBMS transactions have four
properties, which are known as ACID, that ensure consistency of work. There are four major common
concurrency problems that can be solved by using two models of concurrency: pessimistic and optimistic.
We can complete work in SQL Server with any of these five types of isolation levels.

ALL RIGHTS RESERVED TO SVTI 148


CHAPTER 23

DATABASE OBJECTS
The system views are views that contain internal information about a Database. The master database for
example contains information about the SQL Server itself, while the msdb database contain information
about the SQL Server agent and each database has its own system views/tables.

In this article we will show how to get the list of tables, views, stored procedures, how to get a list of
tables of all the databases, how to find a table in multiple datatabases, how to get the list of users, logins,
mapped logins, how to detect a fragmentation in a table and more.
Let’s start with some common questions about databases that can be solved with the system
views/tables/functions:

How can I get the list of tables in a database?


The following queries can provide you with that information about the database tables:

Option 1

SELECT * FROM [INFORMATION_SCHEMA].[TABLES


Option 2
SELECT *
FROM sysobjects WHERE xtype = 'U'

You can use schema views (the INFORMATION_CHEMA.TABLES) or the sysobjects views directly.
According to the books, it is better to use the INFORMATION_SCHEMA views because the internal
structure will not change in the future. The sysobjects view contains useful information about the different
database objects.
Xtype is the type of object and the possible values are:
SQ = Service Queue
TA = Assembly (CLR) DML trigger
TF = Table-valued-Function
TR = Trigger
TT = Table Type
U = User Table
UQ = Unique Constraint
V = View
X = Extended stored procedure

How can I get the list of views in a database?


The solution is similar than the list of tables. There are 2 options to solve this problem:
Option 1
SELECT *
FROM [INFORMATION_SCHEMA].[VIEWS]

ALL RIGHTS RESERVED TO SVTI 149


Option 2
SELECT *
FROM sysobjects
WHERE xtype = 'V'

[INFORMATION_SCHEMA].[VIEWS] contains information about the views or you can find the
information in the sysobjects view.
How can I get the list of procedures in a database?
There are 2 options to solve this problem:

select * from [INFORMATION_SCHEMA].[ROUTINES]


where routine_type='PROCEDURE'

SELECT *
FROM sysobjects
WHERE xtype = 'P'

[INFORMATION_SCHEMA].[ROUTINES] contains information about stored procedures and


functions. The sysobjects is a second option to get this information.

How can I get the creation date of a specific table?


The following T-SQL code shows the creation date of the table ProductDocument:
SELECT crdate
FROM sysobjects
WHERE xtype = 'U'
and
name ='ProductDocument'

Crdate is the creation date and sysobjects is the view that contains most of the database objects including
tables, views, stored procedures and functions.
How can I get the list of all the tables in all the databases?
The sp_MSforeachdb, is a very useful stored procedure that helps to work with all the databases. For some
reason, this stored procedure is not documented.

DECLARE @cmd varchar(8000)


SELECT @cmd = 'USE ? SELECT ''?'',name FROM sysobjects WHERE xtype = ''U'''
EXEC sp_MSforeachdb @cmd

The ? is the database name. It will show the result of the query in each database.
How can I search a table in all the databases?
This is a classical problem. The user created a table, but he does not remember where it was created and
there are multiple databases where we need to search.
The following example shows how to find a table named test in all the SQL Server databases. The query
will show the database(s) and the table.
ALL RIGHTS RESERVED TO SVTI 150
DECLARE @cmd varchar(8000)
SELECT @cmd = 'USE ? SELECT ''?'',name FROM sysobjects WHERE xtype = ''U'' and name=''test'''
EXEC sp_MSforeachdb @cmd

How can I get the list of stored procedures names and their code?
The syscomments view contains very useful information about the stored procedure, triggers, checks and
other SQL Server objects. You can check the code of your procedures, triggers and other objects. The
sysobjects contains the stored procedure name and the syscomments the code. This query is very useful
to find some words in multiple stored procedures at the same time.

SELECT name, [text]


FROM sysobjects o
INNER JOIN syscomments c
ON
o.id=c.id
WHERE xtype = 'P'

How can I get the creation date of a specific database user?


The sysusers view contain useful information related to the users in a database. The following sample
shows the creation date of the public database user.
select createdate from [sys].[sysusers]
where name='public'

How can I get the creation date of a specific SQL Server Login?
The Login allows to login to the SQL Server database and the database user contains permissions to access
to specific databases. The following query shows the creation Date of a specific Login:
select * from
[sys].[syslogins]
where name='sa'

How can I get the Login and the user mapped in all the databases?
This information is in the sys.database.principals and syss,server.principals. You will find the Login and
the database user mapped to it.
DECLARE @cmd varchar(8000)
SELECT @cmd =

'SELECT ''?'',login_name = sp.name, user_name = dp.name


FROM ?.sys.database_principals AS dp
INNER JOIN sys.server_principals AS sp
ON dp.[sid] = sp.[sid]'

EXEC sp_MSforeachdb @cmd

How can I detect the fragmentation of a specific table?


Multiple inserts, deletes can produce fragmentations in the databases. In earlier versions, the DBCC
SHOWCONTIG sentences were used to detect fragmentations. Now, we use the
sys.dm_db_index_physical_stats function. The column that you need to check is the
avg_fragmentation_in_percent. If the percentage is high, you may need to reorganize or rebuild the

ALL RIGHTS RESERVED TO SVTI 151


indexes of your table. The following sample with shows the fragmentation information about the
[Purchasing].[PurchaseOrderDetail table.
DECLARE @db_id SMALLINT;
DECLARE @object_id INT;
SET @db_id = DB_ID(N'AdventureWorks2012');
SET @object_id = OBJECT_ID('[Purchasing].[PurchaseOrderDetail]');
SELECT avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(@db_id, @object_id, NULL, NULL , 'LIMITED');
GO

If the fragmentation percentage is higher than 30%, it is better to rebuild the index. If it is lower than 30%,
you can just reorganize the index.

How can I get the information about the SQL Server sessions?
The [sys].[dm_exec_sessions] view contains useful information about the sessions like the start time, end
time, login name, NT domain, program used and more.
SELECT *
FROM [sys].[dm_exec_sessions]

How can I get information about the creation date of a backup?


You can find the start date and end date of a database backup in the backupset table.
SELECT
[backup_start_date],
[backup_finish_date]
FROM [msdb].[dbo].[backupset]

How can I get information about the size in MB and location of a backup?
You can also find very useful information about the backup file size and the path of the backup using the
backupfile system table. The following sample shows the size of the backups in MB and the path where
it is located. This information is stored in the msdn database. The backup file_size is stored in bytes, that
is why it is necessary to convert the value to MB.
SELECT
[file_size]/1024/1024 as Size_in_mb
,[physical_name]
FROM [msdb].[dbo].[backupfile]

How can I get information about creation date and modification date of a SQL Server Job?
There is a lot of information about SQL jobs in the MSDB database, dbo.sysjobs table. All the information
related to the agent is stored in the MSDB database.

SELECT
[date_created]
,[date_modified]
FROM [msdb].[dbo].[sysjobs]

ALL RIGHTS RESERVED TO SVTI 152

You might also like