Documente Academic
Documente Profesional
Documente Cultură
Better Understanding of
Computer Programming
Saikat Basak
www.enselsoftware.com -1-
Better Understanding of Computer Programming
Disclaimer
The author had made every effort in the preparation of this book to ensure the
accuracy of the information. However, the information contained in this book is
provided without warranty, either express or implied. The author will not be
held liable for any damage caused or alleged to be caused either directly or
indirectly by this book.
For the latest version of this book, please see at the web site.
www.enselsoftware.com -2-
Better Understanding of Computer Programming
Contents
1. INTRODUCTION ........................................................................................................................................ 4
15. WHAT LANGUAGE AND CLIENT/SERVER YOU SHOULD USE? .......................................... 118
www.enselsoftware.com -3-
Better Understanding of Computer Programming
1. Introduction
What’s special about this book? Well, a lot! I designed the book to be read
online. You can download this book FREE of cost and read at your computer
anytime! You can directly copy the source codes from here and run them in
your favorite compiler!
This book is for a little bit experienced programmers. Here I’ve discussed and
tried to clarify some difficulties faced by programmers. I didn’t teach any
programming language from scratch here. I assume that you know at least any
one of C/C++, Java or Visual Basic or any other standard programming
language. Although a large part of this book deals with VB/.NET and C++,
other language programmers will also find the information useful. Wherever
possible, I tried to make the discussion in language independent way. However,
to give examples one must use some languages. So I mainly used VB and C/++.
I also made a comparison of object-oriented concept among various languages.
Object oriented programming is a hot topic nowadays and very few books
discuss them from practical viewpoint. (Such books are available in C++ and
Java but they are rare for Visual Basic) Here I presented same object oriented
program source code in different languages and discussed how they do differ.
All real world programs are huge and they can’t be discussed in a single book.
However, I delineated how to write elegant, maintainable code. Whatever be
your platform or language, you need to follow certain conventions.
While reading the book, I expect active participation from your part. Reading
like a storybook won’t help. You must understand each concept properly. If you
face any problem, please feel free to contact me. I’m just an email away! My
email is saikat_basak@yahoo.com and my web site is located at
www.enselsoftware.com.
You might notice that the chapters in the book have been arranged in a little bit
haphazard manner! Well, I deliberately did so in order to make you not feeling
bored!
www.enselsoftware.com -4-
Better Understanding of Computer Programming
You must not forget that nothing is more important than a good algorithm. Your
program’s performance mainly depends on the algorithm you adopted rather
than on the language you are using for development!
Since this book discusses many topics at once, I often advised you to read some
other books on those particular topics so that you get a better grasp of the
concepts.
Now sit back, relax and start reading. Have a happy programming!
www.enselsoftware.com -5-
Better Understanding of Computer Programming
Functions are one of the most frequently used components in any programming
language. Typically a function takes some arguments, performs some
calculation and then returns the result to the calling function. However, there are
differences between C and VB on how the functions return values. In C, by
default, a function always returns a single value (or no value at all i.e. void). But
in VB, a function must return a single value. In C, we may force a function
returning multiple values by using pointers. But in VB, we shall have to use Sub
Procedures to return multiple values. The Sub Procedure can return no value,
single value or multiple values. So, in VB, function is a special kind of sub
procedure, which returns single value. In C, function always passes argument by
value. To make it pass argument by reference, we need to pass the addresses of
its arguments, (which is known as pointer). But in VB6, function (and
procedures as well) always pass values by reference (i.e. address) unless
specifically told to pass by value. However, in VB.NET, it is passed by value by
default as in C. In VB.NET, you must specify ByRef explicitly to pass by
reference.
First we shall see how to return single value from a function in C and then in
VB. Study the following simple C code.
Code 2-1
www.enselsoftware.com -6-
Better Understanding of Computer Programming
{
int a;
a = l * w;
return a;
}
Code 2-2
www.enselsoftware.com -7-
Better Understanding of Computer Programming
Code 3-1
#include <stdio.h>
#include <math.h>
void main(void)
{
int a,b,c;
float root1,root2;
int status;
determ=q*q-4*p*r;
www.enselsoftware.com -8-
Better Understanding of Computer Programming
return 0;
}
else /* real root exists */
{
*q1=((-q)+sqrt(determ))/(2*p);
*q2=((-q)-sqrt(determ))/(2*p);
return 1;
}
}
The same program is written in Visual BASIC as shown in code 3-2. The
program has a form and a command button. See the similarities and differences
between a C and VB program.
Code 3-2
Option Explicit
Public Sub solve_quadratic(ByVal a As Integer, ByVal b As
Integer, ByVal c As Integer, ByRef root1 As Single, ByRef
root2 As Single)
Dim determ As Integer
determ = b ^ 2 - 4 * a * c
If determ < 0 Then
MsgBox ("No real root")
ElseIf determ >= 0 Then
root1 = (-b + Sqr(determ)) / (2 * a)
root2 = (-b - Sqr(determ)) / (2 * a)
End If
End Sub
For a sample run, use following values: a = 1, b = -5, c = 6. The roots are 3 and
2.
www.enselsoftware.com -9-
Better Understanding of Computer Programming
In VB, a Function always returns a single value. Whereas, Sub procedures can
return zero, one or more values.
Now we shall see how to write the same program in Java! I am showing here an
entire applet code. However, the main part of the multiple value returning is
shown blue.
Code 3-3
// a quadratic equation solver
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
www.enselsoftware.com - 10 -
Better Understanding of Computer Programming
// add button
JButton jb = new JButton("Solve"); // button label
jb.setActionCommand("SolveEquation"); // button action
command
jb.addActionListener(this);
contentPane.add(jb);
}
www.enselsoftware.com - 11 -
Better Understanding of Computer Programming
jtfr2.setText(String.valueOf(sc2.root2));
}
}
}
}
class SolveClass
{
static double root1,root2;
determinant = b*b-4*a*c;
if(determinant > 0)
{
System.out.println("Two real roots");
scf.root1 = (-b + Math.sqrt(determinant))/(2*a);
scf.root2 = (-b - Math.sqrt(determinant))/(2*a);
}
else
{
scf.root1 = 0;
scf.root2 = 0;
System.out.println("No real root");
}
return scf;
} // end of method Solve
} // end of class SolveClass
In Java , basic data types (like integer, float etc.) are always passed by value.
Only objects can be passed by reference in Java. Observe that two achieve this
task, we had to create two similar object instances inside main. Also, Java
doesn’t support pointers. Pretty peculiar, ha!
www.enselsoftware.com - 12 -
Better Understanding of Computer Programming
It simply returns the square of an integer. Now see the same code written
differently.
Did you now realize the difference? Both functions perform essentially the same
thing. In second function, instead of explicitly returning a value, we are passing
the same by reference (i.e. why we use pointers!). That means, in C, though we
have only functions, using pointers we can perform the same task as those of
procedures in VB or Oracle.
Since VB, Java, Oracle etc. don't have pointers, they use 'function' and
'procedure' both to perform the essentially same task as I’ve shown above.
Internally whenever you use 'procedure' in Java, VB or Oracle, all parameters
are passed/returned by reference by default. But in VB you do have the option
to control whether you want it to be passed by value or by reference.
We’ll see another version of code 3-1 in chapter 24 when we discuss pointers in
detail.
www.enselsoftware.com - 13 -
Better Understanding of Computer Programming
4. Recursive function
A recursive function is really a wonderful thing! If you know how to use it, you
can save lots of lines of code. Following is a VB code to find out the sum of
series 1 + 2 + 3 + … + N.
Code 4-1
Option Explicit
Public Function Sum(i As Integer) As Integer
If i = 1 Then
Sum = 1
Else
Sum = i + Sum(i - 1)
End If
End Function
Please don’t input –ve value! If you input very large N (say 10000), you might
get “Out of Stack space” error. How can you increase stack space?
Most books close the chapter on recursion by just giving you factorial program.
There are several worthwhile applications of recursions in real life problems.
Here I am going to show you how you can recursively traverse a tree using
recursion.
A tree is a non-linear data structure (ouch)! Arrays are linear data structures.
You can travel along an array using a straight line; obviously you can’t do that
in case of trees!
Consider the tree shown in figure 4-1. We need to visit every node of the tree
once and fetch the information from that node. Code 4-2 describes the algorithm
for doing that.
www.enselsoftware.com - 14 -
Better Understanding of Computer Programming
3 4
2
11
10
6
5
12
7 8 9
Figure 4-1
Code 4-2
Function TraverseNode (StartNode as Node)
If StartNode has Children Then
For each Child
Get node information
Call TraverseNode (Child)
Next
Else
Exit Function
End If
The above algorithm makes a pre-order traversal of the tree – in the following
sequence – 1, 2, 5, 6, 3, 7, 8, 9, 4, 10, 11, 12.
To learn more about Trees and traversal methods, please see a Data Structure
textbook.
Code 4-3 shows the VB.NET code for above algorithm. To test it – insert a tree
view control in a sample VB.NET project. Add one command button as well.
Write code to add some elements in the tree view (that code is not shown here).
Only the code for tree traversal is shown below.
Code 4-3
Private Sub TraverseTree(ByVal n As TreeNode)
MessageBox.Show(n.Text)
Dim aNode As TreeNode
For Each aNode In n.Nodes
TraverseTree(aNode)
www.enselsoftware.com - 15 -
Better Understanding of Computer Programming
Next
End Sub
The code adds some sample nodes. You can add some more of your own. The
TraverseTree procedure displays information about every node. Instead of
msgbox, you can use Print #1, to write the node information in a file so that
you can re-load the entire tree by just reading the file. The same procedure, with
little modification, can be used to search for an item in the tree.
Exercise 4-1
Write a program for permutation using recursion. For example, if you give input
as “abc” it will show all possible permutation of the word i.e. abc, acb, bac, bca,
cba, cab.
www.enselsoftware.com - 16 -
Better Understanding of Computer Programming
What is DLL?
DLL stands for Dynamic Link Library. This is a feature of Windows family of
operating systems and OS/2 that allows executable routines to be stored
separately as files with DLL extensions and to be loaded only when needed by a
program.
A dynamic-link library has several advantages. First, it does not consume any
memory until it is used. Second, because a dynamic-link library is a separate
file, a programmer can make corrections or improvements to only that module
without affecting the operation of the calling program or any other dynamic-link
library. Finally, a programmer can use the same dynamic-link library with other
programs.
Let’s examine the topic in more detail. You’re familiar with writing
#include<stdio.h> in your C programs. Aren’t you? In a similar way, you
can define some of your functions, which you often use in many programs, in
your own header file. (Note: I am saying header file for brevity only. It can be
any file for example BAS module file in VB etc.)
Code 5-1
int solve_quad(int p, int q, int r, float *q1, float *q2)
{
float determ;
determ=q*q-4*p*r;
*q1=((-q)+sqrt(determ))/(2*p);
*q2=((-q)-sqrt(determ))/(2*p);
return 1;
}
Now I wrote ten applications where I used this solve_quad function by just
stating #include “MyFile.h” and then calling the function as status =
solve_quad(a,b,c,&root1,&root2). Suddenly I realized that if the
determinant is less than zero, then my programs were going to crash!
www.enselsoftware.com - 17 -
Better Understanding of Computer Programming
Code 5-2
determ=q*q-4*p*r;
However, the trouble starts now! To update all those applications compiled with
code 5-1 by Code 5-2, I need to re-compile each of them! So I have to re-build
all the executables that were using code 5-1. Obviously this is a big problem!
Now suppose I wrote the code 5-1 in a DLL named “MyFild.dll”. Then while
compiling my applications those use code 5-1, I told them that I was going to
supply the solve_quad function dynamically from MyFile.dll. After this as
usual I discovered my folly and replaced code 5-1 with code 5-2 in MyFile.dll.
However, at this time, I don’t need to rebuild all the executables again. All I
have to do is to update the old MyFile.dll (that were using code 5-1) with new
MyFile.dll (which has been compiled with code 5-2)! Doesn’t it seem nice,
really?
You might ask what would have happened if I changed the function look like
double solve_quad(int p, int q, int r, float *q1, float *q2) in
code 5-2? Well, in that case DLL trick wouldn’t have worked! DLLs require
once you told your client applications that you are going to provide a particular
‘interface’ (for this point of time you can assume that interface is somewhat
similar to function prototype), you can’t change that. If you do so, you need to
re-compile all your applications to with new version of your DLL. So interface
works like a binding ‘contract’ between your DLL and client applications. As
long as you change the bodies of your function/procedure without changing the
interface, DLL works fine.
www.enselsoftware.com - 18 -
Better Understanding of Computer Programming
Now I think you have understood the usefulness of DLLs. When we discuss
COM later, you will realize that DLLs are meant for more efficient code re-use
along with many other benefits such as efficient memory usage. Why? Because
if several applications use the same DLL, only one copy of that DLL will be
loaded into memory. When the operating system sees that the DLL is no longer
being used by any application, it will be removed from memory. Also, use of
DLLs results in small executable file size compared with statically linked file.
Through memory mapping, Windows is able to load the DLL once into global
heap and then map the address range of the DLL into address space of each
application that loads it. This is shown in figure 5-1.
Global Heap
Process 1 Process 2
Application 1
Application Application
code Application 2 code
Data 1
Data 2
Figure 5-1
www.enselsoftware.com - 19 -
Better Understanding of Computer Programming
To create a very simple DLL in VB.NET, follow the steps as described below.
Code 5-3
Code 5-4
Dim m As New [MyClass].SimpleClass()
MsgBox(m.Sum(5, 6))
7. Now run the MyClient project. Click on command button. You should see
the summation result.
8. Congratulation! You’ve made your first DLL.
GOLDEN RULE OF
PROGRAMMING
THINK FIRST,
CODE LATER.
www.enselsoftware.com - 20 -
Better Understanding of Computer Programming
So far we have learnt how to write DLLs in VB. The main advantage of DLL is
that, if more than one program requires that DLL, only one copy of the DLL
will be loaded into memory. Also, DLL gives you reusable code. You can just
plug-in pre-built DLLs into your project without knowing their internal code.
So, it’s a good practice to keep your often-used functions/procedures in a DLL
file. The concept of DLL is common to nearly all languages. In VB and C++, it
is known as DLL. In Java and Oracle it is known as ‘Package’ (these are not
exactly DLLs but the concept is similar).
Consider the matrix operations for example. It’s used in most engineering
calculations but matrix is absent in most languages. Instead of writing matrix-
handling program every time, you can store them in a DLL. I’m going to tell
you how to do the same in VB.NET.
Create a class library. Add the following code for calculating product of two
matrices. Assume class name is CMath.
Code 5-5
Public Function Product(ByRef FirstMatrix(,) As Double, ByRef
SecondMatrix(,) As Double, ByRef ProductMatrix(,) As Double)
As Integer
'Product of two matrices
'returns 0 if successful
Dim s As Double
Dim i, j, k, L As Integer
Dim RowsInFirstMatrix, ColsInFirstMatrix,
ColsInSecondMatrix As Integer
RowsInFirstMatrix = UBound(FirstMatrix, 1) - 1
ColsInFirstMatrix = UBound(FirstMatrix, 2) - 1
ColsInSecondMatrix = UBound(SecondMatrix, 2) - 1
ReDim ProductMatrix(RowsInFirstMatrix + 1,
ColsInSecondMatrix + 1)
Try
For i = 0 To RowsInFirstMatrix
For j = 0 To ColsInSecondMatrix
s = 0
For k = 0 To ColsInFirstMatrix
s = s + FirstMatrix(i, k) *
SecondMatrix(k, j)
Next
ProductMatrix(i, j) = s
Next
Next
www.enselsoftware.com - 21 -
Better Understanding of Computer Programming
Catch x As System.Exception
MessageBox.Show(x.ToString)
Return 1
End Try
Return 0
End Function
Now compile it to a DLL file. I’m showing here only the code for matrix
product. You should write all matrix operations such as summation, scalar
product, inversion (real tough) etc. I already wrote those functions in a DLL. If
you like to have the source code, don’t forget to send me an email! ☺
In a new project, add the reference to this newly created DLL file. Make an
instance of your matrix class and then call the matrix methods as necessary.
Now to test the product matrix, you may add the following code in form
command button.
a(0, 0) = 1
a(0, 1) = 2
a(1, 0) = 3
a(1, 1) = 4
b(0, 0) = 5
b(0, 1) = 6
b(1, 0) = 7
b(1, 1) = 8
This program also shows how to return an array from a procedure or function.
We took advantage of same concept as discussed in chapter 3 for returning an
array.
In C, to return an array you need to use pointers. I’m showing here how to write
a 2D-matrix multiplication program in C++.
Code 5-6
www.enselsoftware.com - 22 -
Better Understanding of Computer Programming
/* matrix multiplication */
/* example of returning array from a function using pointer */
#include <iostream.h>
#include <stdlib.h>
void main(void)
{
int **p,**matrix1,**matrix2;
int i,j;
int row1,row2,col1,col2;
cout << "Rows Cols for matrix1 eg. 2 2" << endl;
cin >> row1 >> col1 ;
cout << "Rows Cols for matrix2 eg. 2 2" << endl;
cin >> row2 >> col2;
if(col1 != row2)
{
cout << "Multiplication impossible" << endl;
exit(1);
}
for(i=0;i<row2;i++)
matrix2[i] = new int [col2];
www.enselsoftware.com - 23 -
Better Understanding of Computer Programming
p = ProductMatrix(matrix1,matrix2,row1,col1,col2);
// free memory
for(i=0;i<row1;i++)
delete []matrix1[i];
delete []matrix1;
for(i=0;i<row2;i++)
delete []matrix2[i];
delete []matrix2;
for(i=0;i<row1;i++)
delete []p[i];
delete []p;
} // end of main
row1=r1;
col2=c2;
col1=c1;
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
www.enselsoftware.com - 24 -
Better Understanding of Computer Programming
{
s = 0;
for(k=0;k<col1;k++)
s = s + m1[i][k]*m2[k][j];
matrixp[i][j]=s;
}
}
cout << endl << "Inside function The product matrix is"
<< endl;
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
cout << matrixp[i][j] << "\t";
cout << endl;
}
return(matrixp);
} /* end of ProductMatrix */
The code indeed seems little bit confusing! Isn’t it? For a ready reference, you
may use the following example.
| 1 2 | . | 5 6 | = | 19 22 |
| 3 4 | | 7 8 | | 43 50 |
In VB, the entire product matrix was passed by reference. But in C, you’ll have
to return the starting address of the first element of the array i.e.
matrixp[0][0]. Since it was two-dimensional array, you had to use **. In case
of one-dimensional array, you’ll use only *.
I understand that the above C++ code may seem little bit terse. So it needs some
explanation on pointers. Observe that here we are allocating memory
dynamically by new operator. In case of C we had to use malloc function.
Strictly speaking, there is no multi-dimensional array in C! What we see here is
an array of 1-dimensional arrays! In the line p = new int * [rows]; (note
that p is defined as int ** p;) we are creating an array of rows rows where
each of p[0] to p[rows-1] holds an address. The next line inside for loop,
p[i] = new int [cols]; creates the rooms for the columns.
The thing will be clearer from the figure 14-1. Take an example of a 4x4-matrix
p.
www.enselsoftware.com - 25 -
Better Understanding of Computer Programming
0 1 2 3
p[0]
Indicates address of
this place
p[1] * ( p [3] + 2 )
indicates value
p[2] stored at this place
p[3]
Figure 5-2
Code 5-7
Dim n, c, i, j, k As Integer
Dim AA As Double
Try
c = A(0, 0)
For k = 0 To n - 2
For i = k + 1 To n - 1
www.enselsoftware.com - 26 -
Better Understanding of Computer Programming
For j = k + 1 To n
If c = 0 Then
'No unique solution exists
Return 2
End If
A(i, j) = A(i, j) - A(i, k) * A(k, j)
/ c
System.Windows.Forms.Application.DoEvents()
For i = n - 1 To 0 Step -1
AA = A(i, n)
If i = n - 1 Then j = n - 1 : GoTo 100
For j = n - 1 To i + 1 Step -1
AA = AA + x(j) * A(i, j)
Next j
100: x(i) = -AA / A(i, j)
Next i
Catch z As System.Exception
Return 1
End Try
Return 0 'solution successful
End Function
To call the procedure, you may add the following code against a command
button. Here I’ve solved the following set of equations.
x + y + z – 6 = 0, 2x + 3y + z – 11 = 0 and x – 2y – z – 6 = 0
B(0, 0) = 1
B(0, 1) = 1
B(0, 2) = 1
B(0, 3) = -6
B(1, 0) = 2
B(1, 1) = 3
B(1, 2) = 1
B(1, 3) = -11
B(2, 0) = 1
B(2, 1) = -2
www.enselsoftware.com - 27 -
Better Understanding of Computer Programming
B(2, 3) = -1
B(2, 3) = 6
TextBox1.Clear()
If w = 0 Then
For i = 0 To UBound(z, 1) - 1
TextBox1.Text = TextBox1.Text & "X(" & i &
")=" & z(i) & " ¦ "
Next
Else
MsgBox("Error in solution, return value = " & w)
End If
I hope you’ll find this example handy! Note that in the EquationSolve module
used 0 or 1 to indicate the solution was successful. In case of any error, this
parameter will be returned as 0 to the calling module. This is a good habit
because if you have runtime errors in DLL module, you’re gonna to invite
trouble. In this particular program module, I used first element of array as (0,0).
The VB UBound and LBound are very useful functions, which helps us to write
general-purpose array/matrix handling procedures quite easily! There’s another
wonderful function ReDim Preserve, which allows you to write dynamically
growing array without losing its content!
Exercise 5-2
Write a program to copy one matrix into another. The procedure prototype may
look like CopyMatrix(OriginalMatrix( ) As Double, CopiedMatrix( )
As Double). Just have a try. It’s quite easy problem. Remember that the matrix
may be 1, 2 or 3 dimensional.
Using stack, try to convert any expression (for example 2+3/5) into equivalent
post-fix notation (i.e. 2 3 5 / +) and then evaluate the expression. This would be
a much better calculator compared to that comes with Windows! This is a quite
tough problem. (If you get struck, ask me for help!). Please note that stack
function is built in VB.NET.
If the things like stack or post-fix notation appear strange to you, I recommend
that you go through a text book of ‘Data Structures’ and read the following
topics – stack, queue, linked list, searching (binary tree), sorting (merge sort,
quick sort etc.), trees, graph theory etc.
www.enselsoftware.com - 28 -
Better Understanding of Computer Programming
In normal case functions return their values on top of stack. All variables are
stored on stack by default. However, when you use new or malloc the
variables are stored in a special space of memory known as ‘heap’. They remain
in that place until you delete them! So it is a good idea to clear heap using
when you no longer need a variable. If the heap is full, any new or malloc
will fail. So, whenever you do dynamic memory allocation checks if it has been
done properly. If it fails the variable pointer will point to NULL. However,
some recent compilers automatically handle this situation.
www.enselsoftware.com - 29 -
Better Understanding of Computer Programming
There are mainly three types of DLLs that can be written in Visual C++.
1. Win32 console mode DLL and
2. Microsoft Foundation Class (MFC) DLL.
3. COM DLL using ATL (see chapter 19)
1. In Visual C++ (Visual Studio prior to .NET), open a new ‘Win32 Dynamic
Link Library’ project.
2. Name it as ExDLL
3. Add a C++ source code file and write the following code in it.
Code 6-1
#include <math.h>
determ=q*q-4*p*r;
if(determ<0)
{
*q1=0;
*q2=0;
return 0;
}
else
{
www.enselsoftware.com - 30 -
Better Understanding of Computer Programming
*q1=((-q)+sqrt(determ))/(2*p);
*q2=((-q)-sqrt(determ))/(2*p);
return 1;
}
}
Code 6-2
// this files calls a DLL in runtime
// the DLL must be in same folder as of EXE
// specify full DLL path in Project -> Setting -> Link
#include <iostream.h>
void main(void)
{
int i;
int a,b,c;
float root1,root2;
int status;
www.enselsoftware.com - 31 -
Better Understanding of Computer Programming
}
else
cout << "No real root" << endl;
Yes, you can! But in order to call it, you need to write something extra in
C DLL source code.
If you just try to call the above from VB, you will get either 'Bad DLL
calling convention' or 'Entry point not found' error message. In order to
call a C DLL successfully from VB, you'll need to 'tell' the C DLL in that
way. That’s why we need to use _stdcall command.
Modify the Code 6-1 as shown in Code 6-3 and save it as ExDLL.cpp (C/++
source code file).
Code 6-3
www.enselsoftware.com - 32 -
Better Understanding of Computer Programming
#include <math.h>
determ=q*q-4*p*r;
if(determ<0)
{
*q1=0;
*q2=0;
return 0;
}
else
{
*q1=((-q)+sqrt(determ))/(2*p);
*q2=((-q)-sqrt(determ))/(2*p);
return 1;
}
}
Since we shall call this C DLL from VB, we don't need any C EXE to test it.
But we must define a .DEF file to tell VB which functions/variables can be
found from our DLL.
So, in the ExDLL project, add a text file named ExDLL.def and write
following code in it.
Code 6-4
LIBRARY ExDLL
DESCRIPTION My Test DLL
EXPORTS
SquareIt
www.enselsoftware.com - 33 -
Better Understanding of Computer Programming
solve_quad
pi
The EXPORTS command provides ‘entry points of DLLs’. LIBRARY is the name
of DLL without any extension. In DESCRIPTION you can write anything. To add
any extra comment, use semicolon. There are several other commands you can
write in a .def file. We shall discuss them later.
Now compile the DLL. You should not encounter any error message. (There
may be some warning about double to float conversion etc. for this particular
example problem, but you can ignore them)
DLL is now ready. Next we shall see how to call it from VB.
Open a standard EXE VB project. Add a standard module (BAS file). Write the
following code in it. In your computer, the path of DLL may be different. If you
place the compiled DLL file in \WINDOWS\SYSTEM folder, you can just
specify the file name as “exdll” only.
Code 6-5
Declare Function SquareIt Lib "d:\c-
programming\exdll\debug\exdll.dll" _
(ByVal x As Integer) As Integer
Create a command button in the form. In its 'Click' event, write the
following code.
Code 6-6
Private Sub Command1_Click()
Dim z As Integer
z = SquareIt(5)
MsgBox "Square is " & z
Dim a As Integer
Dim b As Integer
Dim c As Integer
Dim s1 As Single
Dim s2 As Single
Dim status As Integer
www.enselsoftware.com - 34 -
Better Understanding of Computer Programming
Now run the VB project. Click on the command button. Everything should be
fine and you will get the expected results! So, you have called a DLL
written in C from a VB application.
You are probably wondering why you should write the C/++ DLL differently
for calling from C/++ and VB EXE. In fact you should not! Now I am going to
show you how to write a DLL in C/++ so that both C/++ and VB EXE will be
able to call it without any modification!
determ=q*q-4*p*r;
if(determ<0)
{
*q1=0;
*q2=0;
return 0;
}
else
{
*q1=((-q)+sqrt(determ))/(2*p);
*q2=((-q)-sqrt(determ))/(2*p);
www.enselsoftware.com - 35 -
Better Understanding of Computer Programming
return 1;
}
}
EXPORTS
SquareIt
solve_quad
void main(void)
{
int i;
int a,b,c,y,z;
float root1,root2;
int status;
www.enselsoftware.com - 36 -
Better Understanding of Computer Programming
Dim a As Integer
Dim b As Integer
Dim c As Integer
Dim s1 As Single
Dim s2 As Single
Dim status As Integer
This version of DLL is noticeably better than that we discussed earlier! The type
BOOL returns an integer – either 1 (true) or 0 (false). The calling convention in
code 6-9 might have been written in another way using GetProcAddress. But I
am leaving that stuff!
Why should I bother writing a DLL in C and call it from VB? I can write
the DLL in VB itself.
www.enselsoftware.com - 37 -
Better Understanding of Computer Programming
Of course you can write a DLL in VB as well. But main advantage of writing a
DLL in C is performance. A program (either EXE or DLL) written in C
generally executes faster than those written in VB. (This sentence needs a little
bit explanation. The speed of your applications mainly depends on the algorithm
adopted rather than on the language you are using. A good VB program can
easily outperform a poorly written C program. Then why it is said the C
program executes faster? Well, take an example of string operations. Normally
in C you use char* to perform string manipulation. But VB does not have
explicit pointers. However, it internally handles strings in the same way as that
of pointers in C. Definitely this internal operation takes some more time than
direct handling of pointers. Similarly i++ executes faster than i = i + 1
because in former case the accumulator in memory directly gets incremented
while in case of the later, variable’s value is first copied into the registers and
then the addition is performed. Moreover VB programs often calls Windows
API functions, which are mostly written in C. Using the same logic, programs
written in assembly or machine languages run fastest because the processor
directly executes them without any translation.) In many applications
speed is significant. Apart from that, I already told you that C could
interact with hardware in much more versatile manner compared to VB. So
often, writing a DLL in C becomes a necessity.
Unfortunately, you can’t. Why? Well, to call a DLL you must know how to call
its functions. Unless the developer of the DLL provides you with the necessary
documentation, you don’t know how to call it. For example, Microsoft tells you
how to call its APIs. So, you can use them. Moreover, some DLLs can’t be used
without registering/licensing. All these registration stuff can be described in a
.def file. These things are quite scary and I shall come to this point later.
#ifndef __AFXWIN_H__
www.enselsoftware.com - 38 -
Better Understanding of Computer Programming
// my code starts
_declspec(dllexport) void WINAPI ThickRectangle(CDC* pDC, int
x1, int y1,int x2, int y2, int t);
_declspec(dllexport) void WINAPI ThickEllipse(CDC* pDC, int
x1, int y1, int x2, int y2, int t);
_declspec(dllexport) void WINAPI ThickPixel(CDC* pDC, int x1,
int y1);
// my code ends
//////////////////////////////////////////////////////////////
///////////////
// CMyDllApp
// See MyDll.cpp for the implementation of this class
//////////////////////////////////////////////////////////////
///////////////
// The one and only CMyDllApp object
CMyDllApp theApp;
CBrush newbrush;
CBrush* oldbrush;
pDC->Rectangle(x1,y1,x2,y2);
pDC->Rectangle(x1+t,y1+t,x2-t,y2-t);
newbrush.CreateSolidBrush(RGB(255,255,0));
oldbrush=pDC->SelectObject(&newbrush);
pDC->FloodFill(x1+(t/2),y1+(t/2),RGB(0,0,0));
pDC->SelectObject(oldbrush);
newbrush.DeleteObject();
}
www.enselsoftware.com - 39 -
Better Understanding of Computer Programming
AFX_MANAGE_STATE(AfxGetStaticModuleState());
CBrush newbrush;
CBrush* oldbrush;
pDC->Ellipse(x1,y1,x2,y2);
pDC->Ellipse(x1+t,y1+t,x2-t,y2-t);
newbrush.CreateSolidBrush(RGB(255,0,0));
oldbrush=pDC->SelectObject(&newbrush);
pDC->FloodFill(x1+(t/2),y1+((y2-y1)/2),RGB(0,0,0));
pDC->SelectObject(oldbrush);
newbrush.DeleteObject();
}
CPen newpen;
CPen* oldpen;
pDC->SetPixel(x1,y1,0L);
newpen.CreatePen(PS_SOLID,2,RGB(255,255,0));
oldpen=pDC->SelectObject(&newpen);
pDC->MoveTo(x1-5,y1);
pDC->LineTo(x1-1,y1);
pDC->MoveTo(x1+1,y1);
pDC->LineTo(x1+5,y1);
pDC->MoveTo(x1,y1-5);
pDC->LineTo(x1,y1-1);
pDC->MoveTo(x1,y1+1);
pDC->LineTo(x1,y1+5);
pDC->SelectObject(oldpen);
newpen.DeleteObject();
}
// my code ends here
Now compile the dll. It should compile without any error message.
To test our generated dll, we need to make an MFC EXE to test it. Create a new
MFCAppWizard(exe) named MyDllExe.
www.enselsoftware.com - 40 -
Better Understanding of Computer Programming
#pragma once
#endif // _MSC_VER >= 1000
// call ThickRectangle
ThickRectangle(pDC,50,300,75,350,20);
ThickRectangle(pDC,150,350,250,450,25);
ThickRectangle(pDC,400,200,700,600,25);
// call ThickEllipse
ThickEllipse(pDC,50,100,75,150,10);
ThickEllipse(pDC,150,150,250,250,15);
ThickEllipse(pDC,450,250,650,550,10);
//////////////////////////////////////////////////////////////
///////////////
// CMyDllExeView diagnostics
www.enselsoftware.com - 41 -
Better Understanding of Computer Programming
As stated before, from Project – Settings – Link tab, specify the full path of
Object/Library module (for the DLL’s LIB file). Now compile the EXE file. Be
sure to copy the DLL file into same folder as of the EXE. Run the EXE and you
should see some colorful boxes and ellipses! In this example, I used some
graphics features of VC++ intentionally to demonstrate a true MFC example.
You can also incorporate the same functions as discussed in console mode DLL
creation. Study the code carefully and you will realize what is the general
procedure to write MFC DLLs! Of course, things may appear Hebrew to you if
you are new to VC++. That’s why I recommend that you read a standard Visual
C++ learning side by side. In fact, there are lots of more things need to be taken
into consideration while developing MFC DLLs. A detail discussion of these
topics is beyond the scope of this book. Honestly speaking, I myself don’t know
all the features of VC++!
Functions using the standard calling convention remove the parameters from the
stack before they return to the caller. In the normal C/++ calling convention, the
caller cleans up the stack instead of the function. Most other language such as
VB or Pascal use standard calling convention by default. The standard calling
convention so named because all Win32 API functions, except few that take
variable arguments, use it. Variable argument functions continue to use C
calling convention of _cdecl. Virtually all functions offered by COM
interfaces on Microsoft platforms use the standard calling convention.
Gee! So you learnt to create both console mode and MFC DLLs in C++! So far
we only exported functions and variables from a DLL. There remains to learn
another important task. How to export classes from a DLL?
Yeah! In Unix, DLLs are known as ‘shared objects’ (*.so) – they work much
like in the same way as that of DLLs in Windows.
Don’t think that DLLs are solutions of all problems! Calling DLLs have traps of
their own! As long as you are passing simple data types (e.g. number, string
etc.) between C and VB you are fine. Trouble starts when you try to pass
complex data types such as array, object etc.
Consider code 5-6 again. It showed how to find out matrix product in C/++.
Now, suppose you want to make it a DLL. You can easily do that in C/++ by
www.enselsoftware.com - 42 -
Better Understanding of Computer Programming
following the methods discussed (dllexport, stdcall or BOOL API etc.) in this
chapter. Calling the DLL from C/++ won’t have any problem. But how do you
call it from VB? Observe that the line in C/++ which calls the function p =
ProductMatrix(matrix1,matrix2,row1,col1,col2) does not have any
direct equivalent in VB!
In C/++ when you state matrix1, you are actually passing the address of the
first element of the matrix. Also the variable p after calling the function contains
an address which stores address of an integer. How do you make VB understand
this glitch? How do you return as user defined structure or object from C/++ to
VB, which does not support that structure or object? So inter operability among
several languages indeed a problem, a big problem. We’ll see in the following
program how to pass a matrix through a C function that returns a structure and
then calling it in VB.
struct quad
{
float r1;
float r2;
char* status;
};
p=*(a+0);
q=*(a+1);
r=*(a+2);
determ=q*q-4*p*r;
www.enselsoftware.com - 43 -
Better Understanding of Computer Programming
x->status=(char*)malloc(13*sizeof(char));
strcpy(x->status,"No real root");
return x;
}
else /* real root exists */
{
x->r1=((-q)+sqrt(determ))/(2*p);
x->r2=((-q)-sqrt(determ))/(2*p);
x->status=(char*)malloc(15*sizeof(char));
strcpy(x->status,"Two real roots");
return x;
}
}
LIBRARY ArrayStructure
EXPORTS solve_quad
z(0) = 1
z(1) = -5
z(2) = 6
adr = solve_quad(VarPtr(z(0)))
Call CopyMemory(Root1, adr, 4)
Call CopyMemory(Root2, adr + 4, 4)
Call CopyMemory(Solution, adr + 8, 4)
MsgBox "Root1 = " & Root1 & vbCrLf & "Root2 = " & Root2 _
& vbCrLf & "Solution = " & Solution
End Sub
www.enselsoftware.com - 44 -
Better Understanding of Computer Programming
Execute the VB6 program and you’ll see two roots and status of solution.
Anyway, back to our business. The adr stores the memory address of quad
structure after calling the solve_quad function. Next the API function
CopyMemory(Root1, adr, 4) assigns the content of address adr into variable
Root1. It copies 4 bytes of data (since we defined Root1 as Single, which also
takes 4 bytes) beginning from address adr.
By the way, these direct memory manipulation functions have been removed
from VB.NET!
Exercise 6-1
Rewrite the code 6-16 using BOOL APIENTRY instead of _stdcall. (Hints:
Suppose you want to call this function inside a C main function. Then you can
also use prototype as void solve_quad(int *a, quad **m). Inside
function, write *m = x instead of return x in code 6-16. While calling the
function, use solve_quad(z,&w) where z is defined as int z[3] and w as
quad *w. Access structure elements as w->r1, w->status etc. Compare two
different types of declarations of same function in conjunction with “difference
between function and procedure” as discussed in chapter 3.)
Happy exporting!
www.enselsoftware.com - 45 -
Better Understanding of Computer Programming
7. File handling
In this chapter you learn basic file handling in C and QBASIC. You may ask
that why I am going to discuss this very basic file handling technique while they
are normally available in most beginning programming language books. It’s
true. In fact nowadays people rarely use C/++ (leave alone Basic) exclusively
for file handling operation in an application. Mostly a backend database and a
front end user interface are used. However, in very early days of computing,
only one language was used to create everything, from writing to file to
presenting data to user as well. If you ever need to maintain some legacy code,
you might find this kind of file handling in C.
However, I presented the code here in very basic form. For example, the
updating/deletion algorithm adopted here is not very efficient. Moreover, in
actual practice, the records should be stored in binary tree or b-tree format
(normally b-tree format is taken in most large database applications).
Code 6-1 shows the how to create binary file in C and then add, modify,
display, delete, search records in the file and exporting to ASCII as well.
Code 7-1
/* A SIMPLE DATABASE OPERATION PROGRAM */
/* (c) Saikat Basak */
/* COMPILED IN TURBO-C/C++, also compiles in Visual C++ */
/* the program should also compile in UNIX */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main(void)
{
FILE *fp,*ft,*fx;
int choice, another,n;
struct person
{
char name[30+1];
char address[50+1];
char phone[10+1];
};
char myname[30+1];
struct person man;
long int recsize;
fp=fopen("data.dat","rb+");
www.enselsoftware.com - 46 -
Better Understanding of Computer Programming
if(fp==NULL)
{
fp=fopen("data.dat","wb+");
if(fp==NULL)
{
puts("Can't open file");
exit(0);
}
}
recsize=sizeof(man);
while(1)
{
puts("------------------------------");
puts("A simple database application");
puts("------------------------------");
printf("1. Add Record\n");
printf("2. Display\n");
printf("3. Modify\n");
printf("4. Delete\n");
printf("5. Search\n");
printf("6. Export to text\n");
printf("7. Exit\n");
switch(choice)
{
case 1:
fseek(fp,0,SEEK_END);
another=1;
while(another==1)
{
printf("Enter name\n");
scanf(" %[^\n]s",man.name);
printf("Enter address\n");
scanf(" %[^\n]s",man.address);
printf("Enter phone\n");
scanf(" %[^\n]s",man.phone);
fwrite(&man,recsize,1,fp);
printf("Add another? 1 for yes\n");
scanf("%d",&another);
}
break;
case 2:
rewind(fp);
while(fread(&man,recsize,1,fp)==1)
www.enselsoftware.com - 47 -
Better Understanding of Computer Programming
printf("%s %s
%s\n",man.name,man.address,man.phone);
break;
case 3:
another=1;
while(another==1)
{
printf("Enter name to modify\n");
scanf("%[^\n]s",myname);
rewind(fp);
while(fread(&man,recsize,1,fp)==1)
{
if(strcmp(man.name,myname)==0)
{
printf("Enter new name\n");
scanf(" %[^\n]s",man.name);
printf("Enter new
address\n");
scanf("
%[^\n]s",man.address);
printf("Enter new
phone\n");
scanf("
%[^\n]s",man.phone);
fseek(fp,-
recsize,SEEK_CUR);
fwrite(&man,recsize,1,fp);
break;
}
}
printf("Modify another record? 1 for
yes\n");
fflush(stdin);
scanf("%d",&another);
}
break;
case 4:
another=1;
while(another==1)
{
printf("Enter name to delete\n");
scanf("%s",myname);
ft=fopen("temp.dat","wb+");
rewind(fp);
while(fread(&man,recsize,1,fp)==1)
{
if(strcmp(man.name,myname) != 0)
fwrite(&man,recsize,1,ft);
}
www.enselsoftware.com - 48 -
Better Understanding of Computer Programming
fclose(fp);
fclose(ft);
remove("data.dat");
rename("temp.dat","data.dat");
fp=fopen("data.dat","rb+");
case 5:
rewind(fp);
printf("Enter name to search for (you may
input first few characters)\n");
scanf("%s",myname);
n=strlen(myname);
while(fread(&man,recsize,1,fp)==1)
{
if(strnicmp(man.name,myname,n)==0)
{
printf("%s %s
%s\n",man.name,man.address,man.phone);
}
}
break;
case 6:
fx=fopen("data.csv","w+");
rewind(fp);
while(fread(&man,recsize,1,fp)==1)
fprintf(fx,"%s,%s,%s\n",man.name,man.address,man.phone);
fclose(fx);
printf("File contents has been exported to
data.csv\n");
break;
case 7:
fclose(fp);
exit(1);
}
}
}
Study the above program carefully. There are some new functions. The same
program is again made in QBASIC as given in Code 6-2. Here TYPE is
equivalent to struct of C. GET and PUT are similar to fread and fwrite of C.
www.enselsoftware.com - 49 -
Better Understanding of Computer Programming
Code 7-2
5
WHILE (1)
COLOR 10, 3, 2
CLS
LOCATE 5, 25
PRINT "Simple database application"
LOCATE 7, 30
PRINT "1. Add record"
LOCATE 8, 30
PRINT "2. Display"
LOCATE 9, 30
PRINT "3. Modify"
LOCATE 10, 30
PRINT "4. Delete"
LOCATE 11, 30
PRINT "5. Search"
LOCATE 12, 30
PRINT "6. Export to text"
LOCATE 13, 30
PRINT "7. Exit"
LOCATE 20, 25
INPUT "Enter your choice"; choice
CASE 1
CLS
another$ = "y"
OPEN "database.dat" FOR BINARY AS #1 LEN = LEN(MyBook)
OPEN "database.idx" FOR INPUT AS #10
INPUT #10, i
CLOSE #10
DO WHILE another$ = "y"
www.enselsoftware.com - 50 -
Better Understanding of Computer Programming
CASE 2
OPEN "database.idx" FOR INPUT AS #10
INPUT #10, i
CLOSE #10
CLS
PRINT "Displaying records...": PRINT
j = 1
OPEN "database.dat" FOR BINARY AS #2 LEN = LEN(MyBook)
DO WHILE ((NOT EOF(2)) AND (j < i))
GET #2, j, MyBook
PRINT "Name: "; MyBook.myname
PRINT "Address: "; MyBook.myaddress
PRINT "Phone: "; MyBook.myphone
PRINT
j = j + 80
LOOP
CLOSE #2
INPUT "Press any key to continue", x
CASE 3
CLS
OPEN "database.dat" FOR BINARY AS #3 LEN = LEN(MyBook)
INPUT "Enter name to modify: "; whatname
flag = 0
m = 1
DO WHILE NOT EOF(3)
GET #3, m, MyBook
IF MyBook.myname = whatname THEN
flag = 1
INPUT "Enter Name: "; MyBook.myname
INPUT "Enter Address: "; MyBook.myaddress
INPUT "Enter Phone#: "; MyBook.myphone
PUT #3, m, MyBook
END IF
m = m + 80
LOOP
CLOSE #3
IF flag = 0 THEN PRINT "Not found"
www.enselsoftware.com - 51 -
Better Understanding of Computer Programming
CASE 4
CLS
OPEN "temp.dat" FOR BINARY AS #11 LEN = LEN(MyBook)
OPEN "database.dat" FOR BINARY AS #4 LEN = LEN(MyBook)
INPUT "Enter name to delete: "; deletename
flag = 0
p = 1
q = 1
DO WHILE NOT EOF(4)
GET #4, p, MyBook
IF MyBook.myname <> deletename THEN
PUT #11, q, MyBook
q = q + 80
ELSEIF MyBook.myname = deletename THEN
flag = 1
PRINT ""; deletename; " is being deleted"
q = q
END IF
p = p + 80
LOOP
IF flag = 0 THEN PRINT "Record not found"
CLOSE #4
CLOSE #11
CASE 5
CLS
OPEN "database.dat" FOR BINARY AS #5 LEN = LEN(MyBook)
INPUT "Enter name to search for: "; whatname
flag = 0
k = 1
DO WHILE NOT EOF(5)
GET #5, k, MyBook
IF MyBook.myname = whatname THEN
flag = 1
PRINT "Name: "; MyBook.myname
PRINT "Address: "; MyBook.myaddress
PRINT "Phone: "; MyBook.myphone
END IF
k = k + 80
LOOP
CLOSE #5
www.enselsoftware.com - 52 -
Better Understanding of Computer Programming
CASE 6
CLS
OPEN "data.txt" FOR OUTPUT AS #12
OPEN "database.dat" FOR BINARY AS #6 LEN = LEN(MyBook)
u = 1
DO WHILE NOT EOF(6)
GET #6, u, MyBook
PRINT #12, MyBook.myname,
PRINT #12, MyBook.myaddress,
PRINT #12, MyBook.myphone
u = u + 80
LOOP
CLOSE #12
CLOSE #6
PRINT "File has been written to file DATA.TXT"
INPUT "Press any key to continue", x
CASE 7
GOTO 10
CASE ELSE
SOUND 1000, 2
END SELECT
WEND
10 GOTO 200
100 CLS : PRINT : PRINT
PRINT "An error has occurred while accessing the file"
PRINT "Make sure that for options other than 1, the file
must be created first"
INPUT "Press any key to continue", x
GOTO 5
200 END
Look, there are some GO TO statements have been used. Do they always violate
structured programming concept?
You can use the above code in VB with just slight modifications!
Exercise 7-1
www.enselsoftware.com - 53 -
Better Understanding of Computer Programming
Re-write the code 6-1 using C++. Use binary search algorithm. Do you think
use of class instead of structure will be better? You may need to consult a data
structure textbook for the binary tree implementation algorithm. This is a tough
exercise but worth doing!
www.enselsoftware.com - 54 -
Better Understanding of Computer Programming
8. Pointer paradoxes in C
In this chapter I’ll discuss various topics about pointers and shall try to clarify
some of your doubts. Although all C/++ programming books deal with pointers
not all of them provides sufficient insight. You may consult Ref. 9 for a
dedicated treatment of pointers in C.
Did you remember the quadratic equation function in code 3-1? Look, here we
write the function in slight different manner.
Code 8-1
/* a quadratic equation solver in C++ */
#include <iostream.h>
#include <math.h>
void main(void)
{
int a,b,c;
float root1,root2;
int status;
www.enselsoftware.com - 55 -
Better Understanding of Computer Programming
determ=q*q-4*p*r;
Observe that here we passed the root1 and roo2 values by reference (in chapter
3, we did that by pointer). Here we didn’t have to use ‘*’ anywhere in the
program except only an ‘&’ in front of the variable that we want to pass by
reference but that too only in function prototype. C++ is smart enough to do the
rest of work by itself. Note that this code works only in C++ and not in C.
However, the assembly language code generated by the compiler for the
solve_quad function in code 3-1 and 24-1 are same.
Now I am going to tell another nice feature of pointer – the ‘void pointer’! But
before telling you what it is, I like you to think about something else.
When you define something like int a what happens? The compiler reserves 4
bytes of space for variable ‘a’ because size of integer is 4 bytes. What happens
when you write int *a? Here the compiler sees that ‘a’ is an address which can
content an integer. If you try to assign any other data type say float in address
‘a’, the compiler screams. Don’t you wonder that if ‘a’ is just an address why I
can’t store address of any data type? Well, this is for your own safety! We have
to define functions like int Func(float a) because the compiler checks that
we are not mingling inappropriate data types inside anywhere in our programs.
www.enselsoftware.com - 56 -
Better Understanding of Computer Programming
If we do so accidentally, not only it will give erroneous result but also it would
be very difficult to debug the program to find out what went wrong.
Ok, you may argue that for data types, the byte sizes are different. But for
address, I can store any address at any pointer variable because bytes required to
store all addresses are the same. Yes, it is! We can achieve the feat by using
void pointer!
A void pointer variable can hold address of any data type. We define it as void
*a. Now take a look at the next program.
Code 8-2
// demo of void pointer & template
#include<iostream.h>
void main(void)
{
void *gp;
int *ip,i,*j;
i=5;
ip=&i;
cout << "ip = " << *ip << endl;
gp=ip;
j=(int*)gp;
cout << "gp = " << *j << endl;
int a,b;
a=10; b=20;
// swap function used for int
swap((void**)&a,(void**)&b);
cout << "a=" << a << endl;
cout << "b=" << b << endl;
char p,q;
p='P'; q='Q';
// swap function used for char
swap((void**)&p,(void**)&q);
cout << "p=" << p << endl;
cout << "q=" << q << endl;
int m,n;
m=50;n=100;
swap_t(m,n);
cout << "m=" << m << endl;
cout << "n=" << n << endl;
}
www.enselsoftware.com - 57 -
Better Understanding of Computer Programming
The first part of the program gives you an example of simple void pointer
operation. In the next part we find two interesting swap functions. The first
swap function swap uses void pointer. I know you’re going to ask why do we
need ‘**’ in swap function? The answer lies in next line void *temp. This
declaration tells the compiler that temp is an address which can contain the
address of any data type. We can write void temp only because the compiler
has no way to understand how much bytes of memory it need to reserve because
we didn’t specify any particular data type for temp. So to pass a pointer variable
by reference we needed ‘**’. Clear now? Observe another point. In first part of
the program, we wrote j=(int*)gp. Why? Had we written j = gp then the
compiler would have complaint because it would see that gp contains address of
generic data type which we were being trying to assign an address j which
contains address of an integer. So by writing j=(int*)gp we are actually
telling the compiler ‘hey, I know gp contains address of any data type but now I
want it to assign to j which contains address of an integer. I know what I am
doing so don’t panic’. So the compiler obeys the master and works fine.
However, in Unix, you can write j = gp without any compilation error. The
same logic holds for swap((void**)&p,(void**)&q)as well.
Let’s now venture the second swap function swap_t. What does the word
‘template’ mean? It is too actually for generalization of data types. I can call this
template function swap_t to swap integer, float, double, character anything! So
what is the difference between template function and void pointer function.
They are almost the same. When the template function gets compiled, the
compiler generates code for all possible data types (remember function
overloading in chapter 7) an appropriate version is called during runtime
depending on the parameter passed.
www.enselsoftware.com - 58 -
Better Understanding of Computer Programming
Of course, programmers find the template functions are easier to write than that
of void pointers! Do you find this concept similar to that of Variants in Visual
Basic?
Next we’ll learn about linked list. Tell me what does the following structure do?
I am showing here you an example of linked list program. Tries running this
code in debug mode (using line by line execution) and observe the content of
pointer variables.
Code 8-3
/* linked list */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/* function prototypes */
emp* create(struct employee *ptr);
void display(struct employee *ptr);
void search(struct employee *ptr);
void erase(struct employee *ptr);
/* main function */
void main(void)
www.enselsoftware.com - 59 -
Better Understanding of Computer Programming
{
int choice;
employee *p=NULL;
scanf("%d",&choice);
do
{
if(choice==1)
p=create(p);
if(choice==2)
display(p);
if(choice==3)
search(p);
if(choice==4)
erase(p);
scanf("%d",&choice);
int EmployeeId;
char EmployeeName[20];
www.enselsoftware.com - 60 -
Better Understanding of Computer Programming
{
curr=(emp*)malloc(sizeof(emp));
first=curr;
curr->empid=EmployeeId;
strcpy(curr->name,EmployeeName);
curr->next=NULL;
return first;
}
curr=ptr;
curr->next=(emp*)malloc(sizeof(emp));
curr->next->empid=EmployeeId;
strcpy(curr->next->name,EmployeeName);
curr->next->next=NULL;
do
www.enselsoftware.com - 61 -
Better Understanding of Computer Programming
{
if(ser->empid==empnum)
{
printf("%s\n",ser->name);
return;
}
ser=ser->next;
} while(ser!=NULL);
}
}
emp *old;
emp *temp=ptr; /* equivalent of emp *temp = ptr
and then temp = ptr
*/
www.enselsoftware.com - 62 -
Better Understanding of Computer Programming
}
else // item not found
{
old=temp;
temp=temp->next; // point to next item
}
if(flag=0)
printf("Not found\n");
}
}
I know you still have a lot of doubts about pointers (which is not embarrassing
in any way). The best way to learn pointers is to write some programs of your
own and running them in debug mode to examine contents of memory locations.
You may be wondering whether it is possible to write linked list in VB. Yes,
you can. Though VB does not support self-referential structures, it does have
provision for self-referential classes!
www.enselsoftware.com - 63 -
Better Understanding of Computer Programming
We have seen how easy it is to manipulate with strings in VB/.NET and Java. In
early C, there was no ‘string’ data type. We had to muddle with strings with
char* []! But thanks to OOPS in C++, strings are now much easier to play
with. C++ ships with a special type of class called String. It allows us to use
strings in C++ in much like same way we do that in languages like VB or Java.
Just paste the following code in your favorite C++ editor, compile and see the
output. The code is self-explanatory.
Code 9-1
// examples of various C++ string handling functions
#include <iostream>
#include <string>
using namespace std;
// function prototype
string Test(string);
void main(void)
{
// assign strings into variables
string MyName("Saikat"), MyTitle("Basak"), MyFullName;
// concatenate strings using + and display them
cout << MyName + " " + MyTitle << endl;
MyFullName.assign(MyName + " " + MyTitle);
cout << MyFullName << endl;
// string1.append(string2) results in string1string2
cout << MyName.append(MyTitle) << endl;
cout << "Length of my name " << MyFullName.length() <<
endl;
// input string
string x,y;
cout << "Enter two strings e.g. x y" << endl;
cin >> x >> y;
cout << "You entered " << x << " and " << y << endl;
// compare strings
if (x==y)
cout << "Strings are same" << endl;
else
cout << "Strings are not same" << endl;
int f = x.compare(y);
cout << "compare value returned " << f << endl;
// substring
cout << "My first name obtained from my full name is "
<< MyFullName.substr(0,6) << endl;
// finding string
string LongText;
www.enselsoftware.com - 64 -
Better Understanding of Computer Programming
LongText.replace(PositionOfFindWhat,LengthOfFindWhat,"lio
n")
<< endl;
// experiment with other built in string handling
funcions!
// string passed as parameter is function and return
value
string z = Test("India");
}
// end of main
string Test(string x)
{
cout << "String passed as parameter " << x << endl;
return x;
}
Look ma, there’s no pointer! Doesn’t C++ seem easy? Also we’ve passed string
as function parameter and returned string as function value!
www.enselsoftware.com - 65 -
Better Understanding of Computer Programming
We shall see first how to overload a function in C++. The following example
code is self-explanatory. We are trying to find out volume of a box and noting
cube is a box whose all dimensions are equal.
Code 10-1
int volume(int,int,int);
float volume(float);
int main(void)
{
cout.precision(3);
cout.width(10);
cout << "Volume of cube of side 10 is " << volume(10.5)
<< endl;
cout << "Volume of box of length 10 width 5 height 2 is "
<< volume(10,5,2) << endl;
return 0;
}
float volume(float l)
{
float v;
v = l * l * l;
return v;
}
Note that the volume function has been used twice with different parameters
and return values. Similar code can be written in Java as well.
Code 10-2
www.enselsoftware.com - 66 -
Better Understanding of Computer Programming
MsgBox(FindVolume(2, 3, 4))
MsgBox(FindVolume(5.25))
Yawn!
www.enselsoftware.com - 67 -
Better Understanding of Computer Programming
CLASS
Private Data
Area
No Entry
Functions
Data
Public Area
Entry Functions
Allowed
Figure 11-1
1. Objects
2. Data abstraction
3. Inheritance
4. Dynamic binding
5. Classes
6. Data encapsulation
7. Polymorphism
Please note that I shall make no attempt to teach you Object Oriented
Programming from scratch in this book. I expect that you already have at least
basic idea of what OOP is all about. However, I shall help you to clear many of
your doubts normally you might have with OOP.
www.enselsoftware.com - 68 -
Better Understanding of Computer Programming
Basically you can assume that Class is a template from which Object is created.
Classes have no existence of their own. They are like blue prints of plan from
which buildings (i.e. Objects) are made.
Please note that if you are new to OOP, it may seem complicated at first (I felt
the same, too). But later you will definitely realize that OOP is for simpler
programming. That’s why it is so popular nowadays. OOP programs are easier
to write and maintain as well.
Code 11-1 illustrates an OOP concept. First we define class ‘Car’. Then we
define ‘Truck’ by extending ‘Car’. Then we define ‘Bird’. A bird has wings and
it can ‘Fly’. Next we make ‘Aeroplane’. It derives from ‘Car’ and ‘Bird’. (I
won’t blame you if you raise doubt about my sanity after finishing this chapter,
but things are really so wonderful. Believe me!)
A car has engine, wheels, doors etc. So does an aeroplane. A bird has wing and
it flies by flapping its wings. An aeroplane also has wings (made of metal) and
it also flies through starting engine, taxing, taking off and navigating
instruments (wow)!
So, we need to tell our program that both ‘Bird’ and ‘Aeroplane’ can ‘Fly’ but
their flying procedure is different from each other!
Code 11-1
// demonstration of Object Oriented features of C++
// a car building program
#include <iostream.h>
#include <string.h>
www.enselsoftware.com - 69 -
Better Understanding of Computer Programming
char brake[5];
char color[10];
public:
void MakeDoor(int);
void FitWheels(int);
void InstallEngine(struct engine);
void FitBrake(char[]);
void PaintBody(char[]);
};
www.enselsoftware.com - 70 -
Better Understanding of Computer Programming
void Car::InstallEngine(engine e)
{
engine ee;
ee.displacement_L = e.displacement_L;
cout << ee.displacement_L << " L engine displacement" <<
endl;
ee.Power_kW = e.Power_kW;
cout << ee.Power_kW << " kW Power" << endl;
ee.cylinder = e.cylinder;
cout << ee.cylinder << " cylinders" << endl;
strcpy(ee.fuel,e.fuel);
cout << ee.fuel << " engine" << endl;
ee.valve = e.valve;
cout << ee.valve << " valves" << endl;
strcpy(ee.transmission, e.transmission);
cout << ee.transmission << " transmission" << endl;
www.enselsoftware.com - 71 -
Better Understanding of Computer Programming
void main(void)
{
// creating a car
// create Car object
Car MyCar;
cout << "Assmebling MyCar..." << endl;
// assemble the car based on parameters supplied
// attach doors
MyCar.MakeDoor(4);
// fit wheels
MyCar.FitWheels(4);
// engine specification
engine ce;
ce.displacement_L=1.5;
ce.Power_kW=100;
ce.cylinder=4;
www.enselsoftware.com - 72 -
Better Understanding of Computer Programming
strcpy(ce.fuel,"petrol");
ce.valve=16;
strcpy(ce.transmission,"automatic");
// assemble engine
MyCar.InstallEngine(ce);
// fit brake
MyCar.FitBrake("disc");
// paint the car
MyCar.PaintBody("green");
www.enselsoftware.com - 73 -
Better Understanding of Computer Programming
Assmebling MyCar...
4 doors
4 wheels
1.5 L engine displacement
100 kW Power
4 cylinders
petrol engine
16 valves
automatic transmission
disc brake
green color
Car is ready. Have a safe driving...
Now we are making a Truck...
Assmebling MyTruck...
2 doors
6 wheels
6 L engine displacement
250 kW Power
8 cylinders
diesel engine
16 valves
manual transmission
100 cubic meter payload
drum brake
The truck is ready... Do you want to carry your car?
starting engine...
taxing...
taking off...
Flying aeroplane at speed of 300 km/h. Whoosh...
Hmm, pretty complicated code, eh? Study it carefully and you will find this
simple code demonstrates function overriding, simple and multiple inheritance
etc. This code is actually rather straightforward. If you just read the comments
and follow the code thereafter, everything will be transparent to you.
Code 11-2
// demonstration of Object Oriented features of Java
// a console mode program
// main class is oopsdemo
// note: a separate .class file will be generated for each
class
// name of source code file is oopsdemo.java
// define class Car
class Car
{
private int wheels;
private int doors;
www.enselsoftware.com - 74 -
Better Understanding of Computer Programming
www.enselsoftware.com - 75 -
Better Understanding of Computer Programming
}
} // end of class Car declaration
class Truck extends Car
{
private float LoadSpace;
public void FitLoader(int loadvolume)
{
LoadSpace = loadvolume;
System.out.println("Load space = " +LoadSpace);
}
} // end of class Truck declaration
// beginning of main class
class oopsdemo
{
public static void main(String args[])
{
// create a car
Car MyCar = new Car();
System.out.println("Assembling car...");
MyCar.MakeDoor(4);
MyCar.FitWheels(4);
MyCar.InstallEngine(1,100,4,"petrol",16,"automatic");
MyCar.FitBrake("disc");
MyCar.PaintBody("red");
// create a truck
System.out.println("Assembling truck...");
MyTruck.MakeDoor(2);
MyTruck.FitWheels(6);
MyTruck.InstallEngine(2,200,6,"diesel",16,"manual");
MyTruck.FitBrake("drum");
MyTruck.FitLoader(100);
MyTruck.PaintBody("black");
}
} // end of main class oopsdemo
// end of source code
Please note that, the above Java code is not an exact equivalent of C++ code
shown in code 7-1. Here I showed only one extension of class i.e. from Car to
Truck. Since Java does not support multiple inheritance, it is not possible to
include Bird and Aeroplane classes here as those of in C++.
Now here is the VB.NET code for class (in file say VehicleClass.vb).
www.enselsoftware.com - 76 -
Better Understanding of Computer Programming
Code 11-3
Namespace Vehicle
Public Class CVehicle
Inherits System.ComponentModel.Component
End Sub
www.enselsoftware.com - 77 -
Better Understanding of Computer Programming
#End Region
End Class
www.enselsoftware.com - 78 -
Better Understanding of Computer Programming
MyCar.FitWheels(4)
MyCar.MakeDoor(4)
MyCar.FitBrake("disc")
MyEngine.cylinder = 4
MyEngine.displacement_L = 1.1
MyEngine.power_kW = 50
MyEngine.fuel = "petrol"
MyEngine.valve = 16
MyEngine.transmission = "RWD"
MyCar.InstallEngine(MyEngine)
MyCar.PaintBody("green")
End Sub
www.enselsoftware.com - 79 -
Better Understanding of Computer Programming
www.enselsoftware.com - 80 -
Better Understanding of Computer Programming
What is COM?
COM stands for Component Object Model. To learn what is COM, imagine
how you built a car or house using Lego mechano blocks when you were a kid
(if not at present)! Such blocks are like components. Several such blocks make
up the whole car or house! COM is just like that. Using COM, your program
will be a collection of Components. If you need to upgrade a particular
Component, all you need is just to replace that Component instead of re-
building/re-compiling the whole program again!
Does it make sense? Not clear? Ok, think about in a different way. You already
know how to make DLLs. You also know that a DLL written in C can be used
in VB. You also knew that an OCX control created in VB could be run in Visual
C++ or Oracle or even in AutoCAD! So, these are components! A component
itself is a binary code. So, you can attach the component into any program as
long as they do support COM.
Object linking enables you to add a reference to another document from within
your applications open document. So, whenever the data in original document
changes contents of each of the document that contains the linked data, also
changes.
With object embedding, an actual copy of the source data is placed into the
document. If you change the embedded data, nothing happens to the original.
After creating OLE, Microsoft decided that OLE should be extended to enable
applications to not only share data, but also share functionality. This was known
as OLE2.
COM is a specification for creating binary objects that can communicate with
each other. COM specifies strict set of rules that programmers must follow
when creating binary objects.
www.enselsoftware.com - 81 -
Better Understanding of Computer Programming
Figure 19-1 shows memory layout for the abstract base class defined by
following function.
Interface IX
{
virtual void _stdcall Fx1( ) = 0 ;
virtual void _stdcall Fx1( ) = 0 ;
virtual void _stdcall Fx1( ) = 0 ;
virtual void _stdcall Fx1( ) = 0 ;
}
IX
Figure 12-1
You may wonder why I am talking gibberish stuffs! Well, things are really
pretty complicated. In fact, to know COM entirely you must understand all
these nasty stuffs! If you try reading any COM book (which explains internal
architecture of COM) I’m sure you’ll find it mind-boggling.
www.enselsoftware.com - 82 -
Better Understanding of Computer Programming
Interfaces are similar to the timbers in a frame house. The timbers determine the
house’s structure. If you don’t remove the timbers, the structure of the house
remains as it is. You may change the walls for brick to log, but the structure
remains the same. Similarly, components can be replaced to give the application
different behavior though architecturally the application remains same. Thus,
carefully designed architectures can produce highly reusable architectures!
However, such designing is not an easy task!
To find out whether the component supports a particular interface, the client
asks the component for that interface at runtime. For this purpose, the client
uses the IUnknown interface. IUnknown declares a function named
QueryInterface. The client calls QueryInterface to determine whether the
component supports an interface. Remember that all COM interfaces are
required to inherit from IUnknown. Every interface has QueryInterface, AddRef
and Release as first three functions in its virtual table. See figure 19-2.
IX
Client
Virtual Function Table (vtbl) CA
pIX Vtbl pointer QueryInterface QueryInterface
AddRef AddRef
Release Release
Fx Fx
Figure 12-2
I am not going to plunge you further in COM details because a COM book
typically contains more than 1000 pages! But I strongly advice that you do read
a good book dedicated on this subject for a better grasp of the whole thing.
www.enselsoftware.com - 83 -
Better Understanding of Computer Programming
What ATL does can also be done with MFC. But MFC applications tend to be
bulky. However, MFC has much broader ranges of application.
In Visual Studio, you have a program called ‘OLE-COM Object Viewer’. Try
opening a DLL file created in VB by clicking on ‘View Type Lib’ icon. You
will see the IDL created by VB for you. You may also try opening a sample
ATL file as created later in this chapter.
What is IDL?
IDL stands for ‘Interface Description Language’. All COMs are joined together
or with client application using interfaces. It is pretty much like the same way
different machine parts are attached each other using screws, nuts & bolts.
www.enselsoftware.com - 84 -
Better Understanding of Computer Programming
What is CORBA?
Client
Client Proxy
(Stub Code)
Skeleton Code
Object Implementation
Figure 12-3
The IDL compiler also generates stub code that the client links to, and this
translates, or marshals, the programming language data types into a wire format
for transmission as a request message to an object implementation. The
implementation of the object has linked to it similar marshaling code, called a
skeleton, that unmarshals the request into programming language data types. A
different IDL compiler with different language mapping can generate the
www.enselsoftware.com - 85 -
Better Understanding of Computer Programming
skeleton. In this way object method implementation can be invoked and the
results returned by the same means.
1. Write some IDL that describes the inferface to the object(s) that we will use
or implement.
2. Compile the IDL using IDL compiler provided by the particular ORB. This
produces stub and skeleton code. It will convert an object reference to a network
connection to a remote server and then marshal the arguments we provide to an
operation on the object reference, convey them to the correct method in the
object denoted by our object reference, execute the method, and return the
results.
3. Identify the classes (header and implementation files) generated by the IDL
compiler that we need to use or specialize in order to invoke or implement
operations.
4. Write code to initialize the ORB and inform it of any CORBA objects we
have created.
5. Compile all the generated code and our application code with the C++ (or
other language) compiler.
6. Run the distributed application.
www.enselsoftware.com - 86 -
Better Understanding of Computer Programming
Code 12-1
// Quad.cpp : Implementation of CQuad
#include "stdafx.h"
#include "ATLquadratic.h"
#include "Quad.h"
#include <math.h>
//////////////////////////////////////////////////////////////
///////////////
// CQuad
*root1=((-b)+sqrt(determ))/(2*a);
*root2=((-b)-sqrt(determ))/(2*a);
*result = 1;
return S_OK;
}
www.enselsoftware.com - 87 -
Better Understanding of Computer Programming
12. Thus we have made a server COM object. To test it we need a client. We
can use anything as front end. In this example we shall use VB.
13. Open a new project in VB. Add reference to ‘ATLquadratic 1.0 Type
Library’. Make a command button. Add the following code in button click
event.
Code 12-2
Private Sub Command1_Click()
On Error GoTo Hell
Dim MyQuad As Quad
Set MyQuad = New Quad
Dim x As Double
Dim r1 As Double
Dim r2 As Double
x = MyQuad.solve_quad(1, -5, 6, r1, r2)
MsgBox "Root1= " & r1 & vbCrLf & "Root2= " & r2
Set MyQuad = Nothing
Exit Sub
Hell:
MsgBox "No real solution"
End Sub
14. Run the VB project. On clicking the button it should show the roots of the
specified quadratic equation.
15. This is just a very simple example of COM! For further (and real world)
discussion of COM/DCOM/COM+/CORBA etc. I again strongly advise you
to consult books dedicated on these subjects!
16. After step 8, you may note that Visual C++ will itself create an ‘idl’ file
(with lots of other files as well).
www.enselsoftware.com - 88 -
Better Understanding of Computer Programming
Summary
Undoubtedly, this is one of the most difficult chapters in this book. Indeed, the
underlying concept of COM/CORBA is quite terse. So, in this section I shall try
to recapitulate the whole thing.
What is marshaling?
You already know that you can pass parameter to a function either by value or
by reference. Passing by value is easy but passing by reference creates problem.
In Windows, an application can modify contents of memory allocated to its own
process. (If you're wondering what is a process, take it for granted for the time
being that each executable running in memory is a process.) However, an
application can't modify data stored in memory that has been allocated to other
processes. This is where COM comes to rescue!
PROCESS PROCESS
A B
Modified data is
again copied to
same address
space in Process
A
Figure 12-4
www.enselsoftware.com - 89 -
Better Understanding of Computer Programming
procedure is complete, COM copies the new value to the caller procedure. So
we can say that procedure residing in separate process has accessed and
modified data contained in calling process.
In the long run, Microsoft intends to phase out COM by CLR (Common
Language Runtime) which is the base of its .NET technology. All code written
for the .NET platform runs under the control of CLR. However, in order to
ensure compatibility, COM will run without problem along with CLR.
According to Microsoft, code written to run exclusively under the control of
CLR is called ‘managed code’ (Just look at the terminology). All codes that rely
on COM or Win32 API are termed as ‘unmanaged code’ (so as to pursue you in
writing .NET – good business tactics, huh)! Now what is this CLR actually?
CLR was designed to allow a very high level of integration among all languages
of .NET platform namely Visual BASIC.NET, C# etc. Here the executable
instruction compiled into DLLs and EXEs will be in the form of Microsoft
Intermediate Language (MSIL). It is similar to assembly code in the sense that it
contains low level instructions for things being pushed, popped or moved in and
out of registers. However, it contains no dependencies on any particular
operating system or hardware platform. (Sounds similar to Java Runtime?) This
means after and EXE or DLL containing MSIL is deployed on a target machine,
it must undergo a final round of just-in-time (JIT) compilation to transform it
into a machine specific assembly instruction.
Though Microsoft currently has plans to ship CLR in all its Windows platforms,
MSIL gives you potential of running your programs in other platforms as well.
(I wonder whether it will actually happen, because it might break Microsoft’s
monopoly in PC operating system market.)
www.enselsoftware.com - 90 -
Better Understanding of Computer Programming
Whether CLR is really better than COM or not is still a subject of arguments
among the experts. Its internal architecture is noticeably different than that of
COM. It is a new technology. If you are further interested, you may find MSDN
journals/magazines helpful.
www.enselsoftware.com - 91 -
Better Understanding of Computer Programming
In earlier chapters I told you about 2/3-tier architecture. Now I’m going to show
you an example that how VB can be connected to an Oracle database! The
database connectivity is easy. There’s very little trouble on your part. First of
all, you need to know what ODBC is. ODBC stands for ‘Open Data Base
Connectivity’. It is technology using which any program can ‘talk’ to any
database.
Figure 13-1
All you required to do is just to set up the connection. The rest (the real difficult
part) will be automatically handled! Before ADO.NET, Microsoft used other
ODBC technology namely ADO, DAO and RDO. But since they are not used
nowadays, I’m not going to tell you anything about them.
Using ADO/OLE DB, you can access all database (be in Oracle, SQL Server,
Sybase etc.) in a uniform way (this uniform access is the main aim of
ADO.NET)!
Don’t conclude that only VB can be used as front end. Any application that
supports COM can be used as front end with ADO.
In the front end, usually following operations are carried out by the end user.
1. Viewing of data.
2. Insertion, updation and deletion of data.
3. Validation of data before insertion into database.
4. Creation of report.
www.enselsoftware.com - 92 -
Better Understanding of Computer Programming
In our further discussion, we shall use the terms ‘client’ for the front end and
‘server’ for the database in backend.
In this chapter I shall show you how to connect to a database and create front-
end forms using VB.NET. You may definitely ask why I am giving the example
with only VB.NET. The answer is that VB is still one of the most popular
programming language – moreover, the VB.NET code can be easily converted
to C# code.
There are several books available in the market on how to connect VB.NET
with databases and develop forms. Most of them, unfortunately, lack the overall
clarity. So, here I shall try to present the contents in such a way that you can
very quickly implement this in your projects.
Here I shall give example of case 2 and 3. From that, you should be able to
create forms of other cases as well.
You might be prompted to use VB’s Data Form Wizard. However, the wizard
genereated code has following drawbacks – they are too slow for large data sets
(test yourself by querying 50,000 records through wizard generated code the
code given below) and they are difficult to modify. Usually, in real life
applications, wizard generated codes are not used.
In the following example, I present a data grid example in such a manner that it
shows – how to show query result from any SQL to data grid, how to update
records through data grid, how to connect with various databases (e.g. Oracle,
SQL Server etc.)
Create a similar looking form – the menu names will be obvious from code
listing. Name of the form is frmUserDefinedQuery.
www.enselsoftware.com - 93 -
Better Understanding of Computer Programming
The name of the query text box is txtQuery and name of the datagrid is dg (as
used in the code). The db type combo is cboDbType. Other text box names are
obvious from code.
Figure 13-2
www.enselsoftware.com - 94 -
Better Understanding of Computer Programming
ds = New DataSet()
da.Fill(ds, "UserDefinedQuery")
DataGridName.SetDataBinding(ds, "UserDefinedQuery")
DataGridName.CaptionText = "Result of query"
Return 0
Catch q As System.InvalidOperationException
MessageBox.Show(q.Message & vbCrLf & "Try to connect first
before executing query.", "Alert", MessageBoxButtons.OK,
MessageBoxIcon.Error)
Return 1
Catch x As System.Exception
MessageBox.Show(x.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
Return 2
End Try
End Function
cboDbtype.Items.Add("Access")
cboDbtype.Items.Add("Oracle")
cboDbtype.Items.Add("SQL Server")
End Sub
Try
cnn = New System.Data.OleDb.OleDbConnection(connstr)
stbStatus.Text = "Connecting with database..."
cnn.Open()
stbStatus.Text = "Connection successful."
www.enselsoftware.com - 95 -
Better Understanding of Computer Programming
Me.Text = "SQL - " & txtUser.Text & "@" & txtDatabase.Text & "
- " & cboDbtype.Text
Catch x As Exception
stbStatus.Text = x.Message
MessageBox.Show(x.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
End Try
End Sub
Try
Dim i As Integer
i = ShowSqlResultInDatagrid(connstr, txtQuery.Text, dg)
If i <> 0 Then Exit Sub
dg.Expand(-1)
Catch x As Exception
MessageBox.Show(x.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
End Try
End Sub
End Class
www.enselsoftware.com - 96 -
Better Understanding of Computer Programming
This application assumes that database client components are installed and
accessible in your computer during runtime (where you will run this code).
There is another catch – using this method, you can update the underlying table
only if the table has a primary key.
Now we are going to develop a master detail form. Where master record will be
single record instace with all navigational controls (first, last, previous, next
record and insert/update/delete) and detail records in data grid.
Figure 13-3
The form should look like this. The main text boxes are txtProdCode,
txtProdName, txtCategory and txtCategoryDesc (non base table field). Though
in the example, a tab page is being shown, you should feel free to design in your
own way. The datagrid is named as dgD. Menu names will be obvious from the
www.enselsoftware.com - 97 -
Better Understanding of Computer Programming
code. Don’t get fightened by the length of the code, try to comprehened – it is
not very difficult.
Code 13-2
Imports System.Data.OleDb
#Region "Generic common code - but some changes are required "
'***************************************************************
'generic common code, except connection string and sql
'change connection string and SQL as required
'***************************************************************
Dim Conn As OleDbConnection = New
OleDbConnection("Provider=MSDAORA.1;Password=MKM;User ID=MKM;Data
Source=MDB")
Dim ds As DataSet
Dim dv As DataView
'***************************************************************
'for detail part of master detail relationship detail data
'change SQL as required
'***************************************************************
Dim sqlD As String = "SELECT PRODCODE, STARTDATE, ENDDATE, BUYPRICE,
SELLPRICE FROM PRICE"
Dim daD As OleDbDataAdapter = New OleDbDataAdapter(sqlD, Conn)
Dim cmdBldD As OleDbCommandBuilder = New OleDbCommandBuilder(daD)
Dim dsD As DataSet
Dim dvD As DataView
Dim dr As DataRelation
'***************************************************************
Dim cm As CurrencyManager
'***************************************************************
'for detail part
'***************************************************************
daD.Fill(ds, "Price") 'change table name as required
dvD = New DataView(ds.Tables("Price")) 'change table name as
required
'***************************************************************
'for relationship
www.enselsoftware.com - 98 -
Better Understanding of Computer Programming
'***************************************************************
Dim dtProduct, dtPrice As DataTable
dtProduct = ds.Tables("Product")
dtPrice = ds.Tables("Price")
ShowDetail()
End Sub
#End Region
www.enselsoftware.com - 99 -
Better Understanding of Computer Programming
intPosition = cm.Position
objCommand.Connection = Conn
objCommand.CommandText = InsertSql
objCommand.CommandType = CommandType.Text
Try
Conn.Open()
objCommand.ExecuteNonQuery()
MessageBox.Show("Record Inserted", "Title",
MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch q As OleDbException
MessageBox.Show(q.ToString, q.Message, MessageBoxButtons.OK,
MessageBoxIcon.Error)
Catch x As Exception
MessageBox.Show(x.ToString, x.Message, MessageBoxButtons.OK,
MessageBoxIcon.Error)
Finally
Conn.Close()
End Try
FillDataSetAndView()
BindFields()
cm.Position = intPosition
ShowPosition()
End Sub
intPosition = cm.Position
objCommand.Connection = Conn
objCommand.CommandText = UpdateSql
objCommand.CommandType = CommandType.Text
Try
Conn.Open()
objCommand.ExecuteNonQuery()
MessageBox.Show("Record Updated", "Title",
MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch q As OleDbException
MessageBox.Show(q.ToString, q.Message, MessageBoxButtons.OK,
MessageBoxIcon.Error)
Catch x As System.Exception
MessageBox.Show(x.ToString, x.Message, MessageBoxButtons.OK,
MessageBoxIcon.Error)
Finally
www.enselsoftware.com - 100 -
Better Understanding of Computer Programming
Conn.Close()
End Try
FillDataSetAndView()
BindFields()
cm.Position = intPosition
ShowPosition()
End Sub
intPosition = cm.Position
objCommand.Connection = Conn
objCommand.CommandText = DeleteSql
objCommand.CommandType = CommandType.Text
Dim i As Integer
i = MessageBox.Show("Do you really want to delete this record?",
"Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If i = vbYes Then
Try
Conn.Open()
objCommand.ExecuteNonQuery()
MessageBox.Show("Record Deleted", "Title",
MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch q As OleDbException
MessageBox.Show(q.ToString, q.Message,
MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
Catch x As System.Exception
MessageBox.Show(x.ToString, x.Message,
MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
Finally
Conn.Close()
End Try
End If
FillDataSetAndView()
BindFields()
cm.Position = intPosition
ShowPosition()
End Sub
#End Region
#Region "Form specific changed common code - change method bodies for each
form "
'***************************************************************
'Form specific changed common code
'change body of functions/procedures as necessary
'***************************************************************
Private Sub BindFields()
txtProdCode.DataBindings.Clear()
txtProdName.DataBindings.Clear()
txtCategory.DataBindings.Clear()
www.enselsoftware.com - 101 -
Better Understanding of Computer Programming
GTS.BackColor = System.Drawing.Color.GhostWhite
GTS.AlternatingBackColor = System.Drawing.Color.GhostWhite
GTS.ForeColor = System.Drawing.Color.MidnightBlue
GTS.GridLineColor = System.Drawing.Color.RoyalBlue
GTS.HeaderBackColor = System.Drawing.Color.MidnightBlue
www.enselsoftware.com - 102 -
Better Understanding of Computer Programming
GTS.HeaderForeColor = System.Drawing.Color.White
With dgcProdCode
.MappingName = "ProdCode"
.HeaderText = "Code"
.Width = 75
.Alignment = HorizontalAlignment.Left
End With
With dgcStartDate
.MappingName = "StartDate"
.HeaderText = "Start Date"
.Width = 65
.Alignment = HorizontalAlignment.Left
End With
With dgcEndDate
.MappingName = "EndDate"
.HeaderText = "End Date"
.Width = 65
.Alignment = HorizontalAlignment.Left
End With
With dgcBuyPrice
.MappingName = "BuyPrice"
.HeaderText = "Buy Price"
.Width = 65
.Format = "#0.00"
.Alignment = HorizontalAlignment.Right
End With
With dgcSellPrice
.MappingName = "SellPrice"
.HeaderText = "Sell Price"
.Width = 65
.Format = "#0.00"
.Alignment = HorizontalAlignment.Right
End With
With GTS.GridColumnStyles
.Add(dgcProdCode)
.Add(dgcStartDate)
.Add(dgcEndDate)
.Add(dgcBuyPrice)
.Add(dgcSellPrice)
End With
dgD.TableStyles.Add(GTS)
End Sub
#End Region
'***************************************************************
'start of this form's specific code
'***************************************************************
www.enselsoftware.com - 103 -
Better Understanding of Computer Programming
www.enselsoftware.com - 104 -
Better Understanding of Computer Programming
End Class
I tried to write the code in as much generic way as possible. Please observe
following points.
1. After loading the form, click File – Load to show data in the form.
2. To insert a new record in master table, first write all the values of the
record in relevant text boxes (erase shown values by selecting texts in
textboxes and pressing Del key) and then click Record – Insert.
3. To delete a record from master, simple click Record – Delete.
4. To update master record, change values in text boxes as necessary and
click Record – Update.
5. After doing any insert, update or delete in detail grid, click Record –
Update to save changes in database.
6. I also described how you could use data grid formatting.
7. The category description is being read from another table (category),
which has a foreign key relationship with master (product) table’s
CategoryNo column. The following stored procedure in Oracle database
is being accessed in the code.
Don’t worry if you don’t understand the entire code on first round. Read several
times to read a grasp of the thing. If the words like dataset, data adapter,
connection string appears weird to you – please read a VB.NET basic textbook
first!
Happy detailing.
www.enselsoftware.com - 105 -
Better Understanding of Computer Programming
Can you explain a little bit how to implement 3-tier architecture using
ADO and COM?
Clearly the database is the back end. In the front end, we have our client
application in VB. Now how do we implement the business logic in middle tier?
Well, we'll write following code in our middle tier, say in a class module (DLL)
in VB so it would be a COM component.
In your front end, you'll have to call the above procedure to update your
database.
Clearly, you've isolated your business logic in the middle tier using ADO. Also
modifying your business logic involves no change in your front or back end.
Moreover, since you adopted ADO syntax in your business logic code, you
don’t need to change this code if you change your front end or back end
database to some other systems.
First I write a stored function and a stored procedure. Next we shall call it from
VB6. Please note that these are written in Oracle PL/SQL syntax.
Code 13-3
create or replace function MySP(x in number) return number is
begin
return(x*x);
exception
when others then
www.enselsoftware.com - 106 -
Better Understanding of Computer Programming
return 0;
end MySP;
You can call stored procedures in similar way from VB.NET. It has already
been shown in code 13-2.
www.enselsoftware.com - 107 -
Better Understanding of Computer Programming
Source: Ref. 17
www.enselsoftware.com - 108 -
Better Understanding of Computer Programming
1. User Layer
2. Business Layer
3. Data Layer
4. User Connection Layer
5. Database Layer
6. Data Connection Layers
User Layer
The user layer is typically the front end. It may be a browser, VB forms etc.
This is the only layer that interacts with the user. It should contain no business
logic altogether – either implicit or explicit. It is aware of only adjacent business
layer.
Business Layer
Data Layer
All data is maintained in this layer and displayed in user layer. It is similar to
client side ADO record set but not exactly the same in the sense that it is
required even we use any other data connection method other than ADO.
www.enselsoftware.com - 109 -
Better Understanding of Computer Programming
Database Layer
There are several points to be considered. First of all, the data layer consists of
data sets. It is conceptually different from record sets! We keep current and
modified values of each field in data set. When required, we update the database
with new values. Of course, you can use ADO record set to use as your data set.
However, if you base your application on data sets rather than ADO record sets,
then you have no trouble to adopt any new technology that comes beyond ADO!
All you need to do is just change your data connection layer – without affecting
any other layer!
Similarly, if you migrate to different database say from Oracle to SQL server
and vice versa, only the database layer will have to do the necessary change. All
other parts of your application will remain fine!
Now you probably realized that ULA is more refined than typical 3-tier
architecture. It offers more flexibility and easier to maintain! Isn’t it? This
concept is quickly gaining popularity and in near future we are likely to see all
database applications to follow this trend.
www.enselsoftware.com - 110 -
Better Understanding of Computer Programming
Figure 14-1
Remember that it is the code architecture, which determines layering, not the
physical location of modules!
This chapter servers only a basic introduction to ULA. For more information
and implementation of ULA please see references such as 15, 24 etc.
www.enselsoftware.com - 111 -
Better Understanding of Computer Programming
It seems fine, but can you give an example of how to implement the whole
thing?
Frankly speaking, implementing the whole thing is quite demanding! That's the
main reason why this architecture is not followed so widely still now.
Before discussing the implementation of ULA, I like to discuss the necessity of
ULA first in more detail form.
The easiest client server system consists of database at backend and user
interface on front end. Look, there is no separate business layer here. Then
where do we keep our business logic in 2-tier system? Well, we mangle some
business logic into database itself (in the form of stored procedures) and the rest
into user interface itself. In 2-tier applications, we mostly use data bound
control. Remember, whenever a control is data bound, our movement is
restricted to a great extent. First of all, you can never create 3-tier/layered
applications with data bound controls because their very name violates the
'isolation' of layers/tiers concept!
You will definitely ask what is the problem with 2-tier applications. Well, 2-tier
applications are very easy to develop (with the consequence that they are very
difficult to maintain). Here the programmer does not need to scratch his/her
head with many technical implementation problems. In these cases, often the
'connection' part of the system remains hidden from the programmer. For
example, consider Oracle - Developer combination that is quite popular. Here
you have only one way to implement your business logic – just before
modifying records in database. You achieve this task by writing some code in
user interface as well as in the database. Now what is the problem with this
thing?
Well, there are lots of problems. First of all, ask yourself - what a database is
meant for? Obviously for storing data. Isn't it? When you write stored
procedures on database, it has to execute them. It creates an extra burden on
database. Secondly, with data bound controls, you are always connected with
database. More users mean more connection with database. More connection
means more process of different requests. So, there is a good chance that the
database will soon bog down under such heavy load. Wouldn't it be nice if we
connect the database, fetch the query, disconnect it, process the query and then
again just connect and save modified data. Well, ULA actually does that (we'll
discuss this again later).
Next problem is that 2-tier applications are often monolithic. An application
made of Oracle - Developer will need to be discarded entirely if I ever want to
www.enselsoftware.com - 112 -
Better Understanding of Computer Programming
use another database say SQL Server. But in ULA, if you change database only
database layer and connection layer need to be updated. And that's really nice.
Unfortunately, problem of 2-tier doesn't end here! Since the user interface here
is tied up with business logic, change in one affect another to a great extent!
(This change can occur in ULA also, but there the problem is much less since
business logic operates on data set rather than directly on user interface).
So, the main point of saying all this gibberish things is that we want to make an
application that is easily MAINTAINABLE i.e. changing/modifying any part of
the application should be as easy as possible. It should not any way hamper any
part of the system what it should not touch.
Hmm…, I am sure that you're feeling beleaguered by all these hi-fi terms! Rest
assured, thing would become clear gradually.
Let me take the simple example of Car database system that we covered in
earlier chapter. I'll tell you how to implement it using ULA. Granted, there's
very little business logic in this very example, but it servers our purpose
anyway.
First we need a database. Let's make our database in Access. Create all the
tables and relate them with appropriate keys. So our database layer is done.
Next comes data connection layer. We shall use ADO for this layer. All we
need is to create a DSN to tell ADO what database to connect using which
driver. And that's completes our botherations with this layer.
The trick comes with data layer. We shall use 'data set' here. Can't we use client
side ADO record set here? Yes we could! We can simply consider ADO record
set as data layer. But we can do something more! Why not create user-defined
arrays and populate them with ADO record set data? I know, you're going to
grudge why should am I going to make it so cumbersome. Wait, it has a
purpose! Suppose, you use ADO record set as your data layer. After 5 years
from now, there may come another more advanced technology say VDO (no
pun attached).
If you make a separate data layer (using data sets with arrays) - all you should
do is to change the connection from ADO to VDO and populate your existing
data sets with VDO record set (or what so ever) instead of your current ADO
record set. So data layer is made of data sets, which is very similar to arrays that
hold your data. Does it make sense now?
The very next layer is user connection layer. It has the responsibility to display
contents of data layer into user interface. It is not very difficult. We have to
write a function, which takes a data set as input and displays appropriate values
www.enselsoftware.com - 113 -
Better Understanding of Computer Programming
www.enselsoftware.com - 114 -
Better Understanding of Computer Programming
Some
Business Some
Logic Business
Logic
2 – tier architecture
Figure 14-2
ADO Recordset
updated with
modified data
www.enselsoftware.com - 115 -
Better Understanding of Computer Programming
Communicates
with database
www.enselsoftware.com - 116 -
Better Understanding of Computer Programming
Layers are program modules. It can be CLS/BAS files (if you write them in VB)
or C/CPP files (if you code them in C/C++) and so on. In the runtime they will
be DLL/EXE or application server files. So, layers are something using which,
you organize your code for best maintainability.
Typically, it is in the business logic layer where you have the freedom to adopt
object oriented programming. However, if you like, you can code business layer
in procedural programming language as well.
www.enselsoftware.com - 117 -
Better Understanding of Computer Programming
Choice of language
Doesn’t the question seem confusing? Best in what aspect? If you compare with
ease of learning, then definitely VB comes into first position. Before the advent
of VB, Windows programming were a daunting task! Even in nowadays
mastering Visual C++ is not very easy! C is often called a terse language.
Indeed it is! In C, you can’t really do anything worthwhile without using
‘pointer’. But the pointer concept is absent in both VB and Java. It’s true that
pointer is difficult to comprehend. However, C/++ is still the most powerful
language ever developed. With C/++, you can do virtually anything. Though C
is tough but learning C definitely pays off. Programs written in C are executed
fastest (I am excluding assembly language programs which are lightning fast!).
C is much more flexible than any other language. Using C, you can manipulate
your computer hardware to its full extent. Nowadays programmers often use
multi-language concept. Various parts of the applications are written in different
languages. For example, take a typical Client Response Management (CRM)
system. The hearts of all such systems are central databases, which are stored in
servers. End users interact with the database through a front end. VB is a
popular environment for front end. In the back end, the huge databases are
generally manipulated by heavy-duty database programs like Oracle/SQL
Server. The connection between front end and back end is normally managed by
a middle end often written in C. The whole operation may be diagrammatically
shown as below.
My Name
Front End (User Interface) Middle Layer (Business Logic) Back End (Database)
Figure 15-1
This kind of application technique is known as 3-tier architecture. All the layers
need not be in same operating system. The front end may be in Windows or web
based while the main database residing in Unix.
www.enselsoftware.com - 118 -
Better Understanding of Computer Programming
For web based front ends, Java is often used. Though Java is platform
independent, being an interpreted language, Java is much slower (roughly 10
times slower) than programs written in other languages like VB or C/++ etc.
Modern programming languages can ‘talk’ with each other. For example, you
can call a DLL written in C from a VB application. Even databases like Oracle
can take advantage of OCX controls or C codes.
Designing huge corporate databases is a gigantic (and very boring) task! It’s a
subject by itself. There are concepts like Normalization, Master – Detail
Relationship or RDBMS (Relational Database Management System), data
integrity and so on. For more information on this subject, please consult any
standard database-designing textbook.
Often 2-tier architecture is also used. In this case, the database remains in back
end and a front end contains all the business logic. A typical example is Oracle
database with Developer front end. 2-tier applications are easier to develop but
difficult to maintain or extend. If the business logic changes, the entire client
(front end) needs to be recompiled and redistributed. Stored procedures are
commonly used in 2-tier system. Stored procedures are functions written in a
vendor specific dialect of SQL that allow business logic to be stored and run on
the database server. A 2-tier architecture is suitable where only single data
source is employed.
On the other hand, 3-tier system has several advantages. The business logic can
be written in middle tier using any programming language. This can be
deployed as COM/CORBA (discussed in chapter 19). This means computers
running the client applications need only be COM/CORBA aware. Here
updating business logic does not result in rebuilding the client.
Anyway, we went far away from our original question. But my main aim is to
make you realize that all languages are good depending on their appropriate
field of applications.
www.enselsoftware.com - 119 -
Better Understanding of Computer Programming
• Oracle
• SQL Server
• Access
• My SQL
• Sybase
• DB2
• Teradata etc.
Out of these, only MySql is free. However, it's features are pretty limited. For
small application it is fine, but even for medium size applications you'll stumble
into problem with it.
Contrary to popular belief, Access is not a mere desktop database. You can
create commercial application using Access. Access it not only simply database,
it can act as a front end as well. It's not the end, Access can act as front end of
other databases eg. Oracle or SQL Server. I personally think Access is a
wonderful product!
Consider Access when your application will be small to medium size (up to 50
tables, no trigger, not more than 10 users working simultaneously, total database
file size not more than 2 GB, no table contains rows more than 100 000). You
can capture your business logic in Access using DAO or ADO code.
You can use VB to act as front end of your Access database. However, unless
there's some special requirement, you'd be better off with Access front end for
Access database.
www.enselsoftware.com - 120 -
Better Understanding of Computer Programming
Access applications can be divided into two parts - backend Access database
(tables only), front end (forms, queries, reports etc.) and even middle tier (code
modules)! This is useful for multi-user Access applications.
However, Access backend can act only as file server. The benefits of Access
application are several. The files are compact and you can run it in any machine,
which has Microsoft Office, installed. For commercial applications, you can
hide your proprietary code by compiling an Access application (mde file built
from mdb file).
Oracle is the current workhorse in database. It's huge, expensive, feature rich.
Administering an Oracle database requires lots of knowledge of the database
internals. Only large companies can afford Oracle database. But it is robust.
Oracle's recoverability feature is far superior to all its competitors. It's own SQL
processing engine is very powerful. You can keep your main business logics
inside database using stored procedures. Now Oracle has special features to
support Java applications. Oracle runs on both Windows and Unix. It can
support thousands of concurrent users. It's data concurrency and locking
features are excellent.
I have not worked with any other databases. However, Sybase compares with
SQL Server. DB2 is mainly for main frames. Teradata is only for data
warehouse applications.
After database, there comes front end. As I already told you, several
combinations are possible as shown in the table below.
www.enselsoftware.com - 121 -
Better Understanding of Computer Programming
Using Access entirely I have already discussed. So, no repetition any more.
Out of two most popular front ends, viz. VB and Forms, we need to discuss
them in details.
VB as a front end is probably your only choice when you are using SQL Server.
VB has a special data connection layer built exclusively for SQL Server (just
because Microsoft made them both). Remember, when you are using Microsoft
database, you usually need to use it end to end i.e., Windows, SQL Server, VB.
www.enselsoftware.com - 122 -
Better Understanding of Computer Programming
(eg. insert, update, delete etc.) you don't need to write any code (which is not
the case for VB). Features like master detail data display, combo box
implementation, list of values, navigation between forms etc. are built in to
Forms.
The bottom line is, if your database is Oracle, and your application is mainly
database centric, Forms should be the best choice (and Report for reports). But
what does the term database centric means? Well, that's another aspect of
design.
Where do you want to keep your business logic? In database mainly, in middle
tier or in client side? If your business logic is encapsulated mostly in database as
stored procedures, your application is database centric. Your front end will
merely act as a window to manipulate data. Advanced database features like
concurrency and locking are entirely controlled by database server itself.
VB comes to take an edge over Forms, when you need some complex graphics
functionality in front end or you need to do considerable amount of processing
in client side (ie. away from database). In many of today's multi-tiered
applications, the database is often used as data dump only (ie. just to store data
nothing else). Whether this is good or bad that's another issue (will discuss
shortly) but such applications should use VB rather than Forms because Forms
is not suitable for too much manipulation on client side.
So, more your application moves toward client side processing from database
centric processing, VB becomes better choice compared to Forms.
The basic catch behind this idea is merely marketing. Microsoft’s SQL Server is
not so powerful database as that of Oracle’s. So, Microsoft pushes programmers
to turn away from database and devote more energy to middle tier/front end.
www.enselsoftware.com - 123 -
Better Understanding of Computer Programming
But Oracle database itself a robust application capable of doing many things
rather that just working as data dump. Oracle never gets bogged down by
thousands of concurrent users (veteran Oracle DBAs will recall Shared Server
feature). So, Microsoft’s catch line behind disconnected dataset (i.e. connected
data takes up valuable database resources) doesn’t apply to Oracle.
Nowadays Java is more and more being used because of its tight integrity with
web. Oracle offers special memory area called Java Pool to cache java classes
for faster loading during execution. For Java applications, J2EE standard is used
for middle tier, usually these applications are always in Browser + J2EE +
Oracle format.
Now, whether you want to use VB or Java for Oracle database is basically your
own choice. If you have pools of VB developers go for VB/ASP else go for
Java. However, the trend is to go for Java now.
Power Builder is similar to Forms for Sybase database. Delphi is similar to VB.
But nowadays it is rarely used.
www.enselsoftware.com - 124 -
Better Understanding of Computer Programming
Since a lot of people working in software industry come from other than
computer science background, I decided to include this chapter in this book. If
you ever took any formal course in software engineering, you may skip this
chapter.
Feasibility study
www.enselsoftware.com - 125 -
Better Understanding of Computer Programming
Design
Coding
In this phase the design is implemented into codes. Each module is tested
individually before integration. This is known as unit testing.
In this phase, all modules are combined and integrated. The software is tested as
a finished product for all the functionalities. It consists 3 different kinds of
testing.
There are two main approaches for designing test cases – black box testing and
white box testing.
In Black Box testing, the test cases are designed based on without any
knowledge of internal working of the program. That means, test cases only
check whether correct output is found for a specific input. But in White Box
www.enselsoftware.com - 126 -
Better Understanding of Computer Programming
testing, test cases are prepared in such a way so that all logical paths of the
program are executed at least once. I shall explain this method with an example.
3 4
Figure 16-1
Maintenance
www.enselsoftware.com - 127 -
Better Understanding of Computer Programming
Statistics shows that more effort is necessary to maintain software than that of
developing it! Maintenance is done for correcting errors, improving
performance, incorporating new functionalities etc.
Waterfall model – here all the above-discussed steps (i.e. feasibility study,
requirement analysis and specification, design, coding, testing and maintenance)
are followed sequentially.
These steps are followed iteratively until customer says that the product is ok.
www.enselsoftware.com - 128 -
Better Understanding of Computer Programming
1. Planning Process – the customer/client should define the desire feature first.
(Similar to Requirement Analysis in conventional software engineering
term)
2. Small Release – put simple system into production early and update it
frequently. (Doesn’t sound similar to evolutionary prototype model?)
3. Metaphor – follow a common system of names for development and
communication (quite obvious).
4. Simple Design – keep your program as simple as possible. First, provide the
basic funtionalities and then update as required. (This is also not a new
concept – we tend to say, “Make it work first, then make it fast”.)
5. Testing – XP says that test cases should be prepared before the program is
made! This helps for better understanding of the ‘classes’ and ‘functions’
needs to be developed later. All test cases must be performed at every stage
of integration. XP promotes ‘testers’ to the same grade as of programmers
from their ‘back benchers’ status!
6. Refractoring – improve design through out entire development (also this is
not a very new concept)
7. Pair Programming – every function etc. must be written by at least two
programmers! While one will be writing the code, another can visualize the
whole thing in much broader way. Researches show that pair programming
produces better result than working-alone programming.
8. Collective Ownership – all code belongs to all programmers! (I didn’t really
figure out what they did want to say!)
9. Continuous Integration – integrate your system several times a day thus
enabling rapid progress. They argue integrating more frequently eliminates
many integration problems. (Is it? May be! I can’t say anything.)
10. 40-hour week – tired programmers make more mistakes! Keep them away
from overtime. (So nice if only my project leader was able to understand this
naked fact!)
11. Onsite Customer – for better communication, some people must be onsite
interacting with client directly (Again, this is a conventional concept)
12. Coding Standard – all programmers must write their code in same way (Old
wine in new bottle.)
www.enselsoftware.com - 129 -
Better Understanding of Computer Programming
Well, this defined XP. As I already told, all the concepts are not entirely new.
Though I think the most important points are – testing, pair programming,
‘keeping it simple’ concept, integration technique and of course, no-overtime
rule!
For more information regarding XP, view the following web site:
www.xprogramming.com
If you find that following XP you get a better output, don’t forget to send me a
mail. After all, I also need to convince my project leader for not doing work on
weekends! ☺
www.enselsoftware.com - 130 -
Better Understanding of Computer Programming
Error proofing
Here are some common but useful tips for error handling techniques. Some of
them will apply to VB only. But majority of them is applicable to any
programming language. We shall discuss more about error handling later.
ERROR PREVENTION
www.enselsoftware.com - 131 -
Better Understanding of Computer Programming
Debugging techniques
Regarding logical errors, I’ve nothing to say. It’s your task how you want to
implement your logic.
The best way to detect error is observing variables as the program is executed.
In older programs you had to use ‘print’ statement to see the values of variables
during program running. Modern editors allow you to ‘watch’ variables. For
example, in VB if you run the program in break mode or step into mode, you
can see the value of a variable by just keeping the mouse pointer over it.
When you set a break point to a line, the program will run up to that line at a
stretch and then will stop at that line. There from you can choose the following.
In case of ‘Step into’ – the program will continue to execute line by line from
that point onward.
‘Step over’ means the program will execute that module (function/procedure)
without any stopping but then will go back to original calling module.
But the first rule is still first – THINK FIRST, CODE LATER.
Before starting coding, you must have a clear idea what you are going to do. I
strongly recommend that you always write ‘pseudo-code’ first. And also write
extensive comments in your code. The thumb rule is there should be one line
comment for every three lines of code! A code with comments few and far
between is difficult to maintain.
Also follow proper coding standards. Though standards vary among companies
– there are still some guidelines.
www.enselsoftware.com - 132 -
Better Understanding of Computer Programming
" Use descriptive variable names with proper capitalization and follow naming
convention.
" Keep formatting i.e. indentation, space between separate function blocks etc.
properly.
" Before beginning of each module, write what the module is supposed to do.
" In a multi-programmer environment, use source code manager like Visual
Source Safe.
" Take special care about pointers (in C/++).
" Late binding errors are difficult to point out. For example (VB) if you write
Public MyFunc (FormName As Form) or Public MyFunc (FormName
As Object), if not properly coded, the later may give you error “Object
does not support this property or method” at runtime.
" Make provision for garbage collection. Use free/delete in C/++ or
Nothing in VB. Though some languages have features for automatic
garbage collection.
" Avoid COM versioning problem – use binary compatibility.
" Avoid writing too much cryptic code. For example, use If b = True Then
instead of If (b) Then.
" Do not exceed variable range e.g. storing 2E10 in integer.
" Have a clear understanding of how operating system and compiler works. It
will help you to write better and optimized code.
If you still have faults in your programs, don’t worry. Even God can’t write bug
free programs!
Many of the things are common in all languages. So, when you are going to
learn a new language, your first few days will be spent on just learning the
syntax. However, there are few special features in every language. Here, I shall
tell you where to look for change in learning a new language.
Variables
www.enselsoftware.com - 133 -
Better Understanding of Computer Programming
Observe how long a variable name can be! Some languages allow only 8, some
other 32 while the rest up to 255 characters! Also, some special characters
might be prohibited in variable names.
Data types
Control statements
The typical If-Else, For loop, Do-While loop, While-Wend loop, Switch-case
etc. Notice how do you get out of a loop using Exit or Break.
When we talk of classes, we must note that some older programming languages
still do not properly implemented this concept. Do not forget that class
inheritance varies widely among languages (as I already discussed in OOPS).
Functions/Procedures/Methods
Functions are the most important parts of your program. Learn how to pass
parameters by reference or by value! Observe how do you return multiple
values. Can you pass array or object as function/procedure parameters in every
language? (Unfortunately not in many languages!)
Windows controls
If it’s a GUI based language, then obviously you’ll have to learn all common
Window’s controls – command button, text box, label, check box, radio button,
combo box, list box, file open/save dialog box, tab pages, progress bar,
image/picture control, timer control, scroll bars, toolbar, status bar, slider etc.
Error handling
www.enselsoftware.com - 134 -
Better Understanding of Computer Programming
How tight you do the coding, your program is always liable to fail. So, don’t
forget error coding. Learn to handle all possible exceptions!
Throughout this book I stressed inter connection between languages. Find out
how you can use module written in other languages with this new language!
Does this language support COM/CORBA?
Special features
Like every human being, every language is unique in certain field. In C/++ we
have famous pointers! In Java we don’t have any easy way to input anything in
console mode application i.e. no equivalent of scanf in Java! In VB all DLLs
are automatically COM! In Oracle PL/SQL any comparison with NULL always
evaluated as False!
www.enselsoftware.com - 135 -
Better Understanding of Computer Programming
In this section, I’m going little bit off track. I shall unveil to you the power of
spreadsheet applications (though similar features are available in almost all
spreadsheets here I shall demonstrate Microsoft Excel).
I’ll show you how to solve linear programming problems using your favorite
spreadsheet! Linear programming is often required by engineers to solve certain
design problem for example – in operational research and various other
‘optimization’ problems etc. Linear programming can be also be solved in
programs like MATHCAD or MATLAB etc., however, since these
mathematical applications are not very common in design offices, you better bet
on versatile spreadsheets. Do you know spreadsheet is the largest selling type of
application in the world? The procedure presented here are for Microsoft Excel
97/2000, but if you any other spreadsheet like Lotus 123 or Borland Quattro Pro
you will find similar functions in those programs as well. I assume that you are
familiar with basic spreadsheet operations. So, I’m directly going to the
problem. Please make sure that you have installed Analysis ToolPak add-in in
Excel.
Step 1: Define the problem as shown in the figure 19-1, which resembles the
cells of the spreadsheet.
A B
1 X 0
2 Y 0
3 Z =3*B1+4*B2
4 C1 =4*B1+2*B2
5 C2 =2*B1+5*B2
Figure 19-1
Note that in cell B3, the equation for Z has been input. Here cells B1 and B2
stands for variable x and y respectively. The strings in column A is for
understanding purpose only. The constraints are defined in cells B4 and B5.
You may like to note that there are two more constraints that both x and y has to
be positive number. These constraints will later be defined using B1 and B2
cells. After you do this, initially all cells in the range B1:B5 will show 0.
www.enselsoftware.com - 136 -
Better Understanding of Computer Programming
Step 2: Click on ‘Tools’ and then ‘Solver…’ from Excel’s menu bar. The solver
dialog box appears as shown in figure 19-2.
Figure 19-2
Make the ‘Set Target Cell’ box to cell B3, because this cell contains the
definition of our main function Z. Now set the ‘By Changing Cells:’ to
$B$1:$B$2. You can either type the cell range yourself or you can select the
range on the worksheet by clicking the red arrows as shown in the figure. Also
make sure that the ‘Equal To:’ selection is set to ‘Max’ for this problem. When
done, click on ‘Add’ button to specify constraints. When you do so, you will see
following dialog box.
Figure 19-3
Specify the Cell Reference and Constraint (for 4x + 3y <= 80) so that the figure
look like as shown below.
Figure 19-4
www.enselsoftware.com - 137 -
Better Understanding of Computer Programming
In the same way specify the other three constraints namely 2x + 5y <= 180, x
=> 0, y => 0. Click OK when done. After that ‘Solver Parameters’ dialog box
should look like figure 19-5.
Figure 19-5
Figure 19-6
You will of course want to retain solver solution. Now you get the solution as
shown in figure 20-7.
A B
1 X 2.5
2 Y 35
3 Z 147.5
4 C1 80
5 C2 180
Figure 19-7
www.enselsoftware.com - 138 -
Better Understanding of Computer Programming
Obviously the maximum value of Z comes out to be 147.5 and for x = 2.5 and y
= 35. So, our problem is solved.
Exercise 19-1
www.enselsoftware.com - 139 -
Better Understanding of Computer Programming
20. References
Some books have been published in several countries. I stated the edition for the
book that I have read. My own liking/disliking about the books are described
within the square brackets.
2. Inside COM, by Rogerson, Microsoft Press [A good book for learning COM but it
is somewhat terse.]
3. C++ programming with CORBA by Vogel et. al., Wiley [Discusses how to use
C++ for CORBA implementation.]
6. Extreme Programming Explained By Kent Beck [I didn’t actually read the book]
7. Mastering COM and COM+ by Rofail & Shohoud, BPB Publication, ISBN
81-7656-181-9 [Presents COM/COM+/DCOM from beginning. Includes examples on
VB, VC++ side by side. Easy language and lots of examples.]
www.enselsoftware.com - 140 -
Better Understanding of Computer Programming
12. Visual Basic 6 – How to Program by Deitel & Deitel, Prentice Hall, ISBN
0-13-456988-5 [Teaches VB from very beginning to an expert level. Includes graphics,
OOAD and data structures in VB along with many other topics.]
13. Thinking in C++ Vol 1 by Bruck Eckel, Pearson Education, ISBN 81-7808-
297-7 [Discusses all OOP concepts, features and their implementation in C++. Includes
good introduction of OOAD and programming practice. CD contains electronic version of
the book.]
16. Secrets of Software Success by Hoch, Roeding et. al. Harvard Business
School Press, ISBN 1-57851-105-4 [This book lucidly presents insights into what
makes software companies successful. This is a management book rather than a technical
book but it is interesting to read.]
19. Operating System Concepts by Silberschatz and Galvin, John Willey, ISBN
9971-51-275-0 [This is a good textbook of operating system for beginners.]
www.enselsoftware.com - 141 -
Better Understanding of Computer Programming
21. Debugging in C++ by Pappas and Muray, Tata McGraw Hill, ISBN 0-07-
041239-1 [It tells you various ways to debug your C++ programs. It includes Visual
C++ – MFC, DLL, COM, assembly mode etc.]
24. Visual Basic 6 – Error coding and Layering by Tyson Gill, Prentice Hall
PTR ISBN 0-13-017227-8 [This book discusses how to design error handling in
Visual Basic code. It also includes an introduction to layered application design.]
www.enselsoftware.com - 142 -
Better Understanding of Computer Programming
www.enselsoftware.com - 143 -