better understanding of computer programming

143
Better Understanding of Computer Programming www.enselsoftware.com - 1 - Better Understanding of Computer Programming Saikat Basak Last updated: June 2004

Upload: enselsoftwarecom

Post on 13-Nov-2014

2.058 views

Category:

Documents


0 download

DESCRIPTION

What you will find here –• All about returning values, objects, matrices,structures from function/procedure• Applying all object oriented programming concept ina single example in C++, VB/.NET and Java• How to write DLL in VB.NET and C++• Introduction to Software Engineering• Database connectivity fundamentals• COM/CORBA/CLR – how do you use them• Pointers made easy• Concepts of language independent programming andmixed language programming• How to become a more productive programmer• Programming in Spreadsheet• Universal Layered Architecture of databaseapplication programming• How to choose best Client/Server combination• How to create VB.NET master detail forms• Updated for .NET

TRANSCRIPT

Page 1: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 1 -

Better Understanding of Computer Programming

Saikat Basak

Last updated: June 2004

Page 2: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 2 -

© Saikat Basak. All right reserved. First Online Edition: March 2001 Second Online Edition: December 2001 Third Online Edition: June 2004 Electronic version of this book is available at www.enselsoftware.com Downloading the PDF/DOC version of this book is allowed. But any modification of the book is a violation of applicable copyright law. 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. Any suggestion on this book is always welcome.

Page 3: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 3 -

Contents 1. INTRODUCTION ........................................................................................................................................ 4

2. HOW TO RETURN A SINGLE VALUE FROM A FUNCTION?.......................................................... 6

3. HOW TO RETURN MULTIPLE VALUES FROM A FUNCTION? ..................................................... 8

4. RECURSIVE FUNCTION ........................................................................................................................ 14

5. WRITING DLL IN VB.NET ..................................................................................................................... 17

6. WRITING DLL IN C/C++......................................................................................................................... 30

7. FILE HANDLING...................................................................................................................................... 46

8. POINTER PARADOXES IN C................................................................................................................. 55

9. STRING HANDLING IN C++ .................................................................................................................. 64

10. FUNCTION OVERLOADING ............................................................................................................. 66

11. OBJECT ORIENTED PROGRAMMING SYSTEM (OOPS) ........................................................... 68

12. THE WORLD OF DISTRIBUTED COMPUTING – COM AND CORBA...................................... 81

13. DATABASE CONNECTIVITY ............................................................................................................ 92

14. PROGRAM ARCHITECTURE – LAYERED APPROACH........................................................... 109

15. WHAT LANGUAGE AND CLIENT/SERVER YOU SHOULD USE? .......................................... 118

16. SOFTWARE ENGINEERING............................................................................................................ 125

17. EXPLORING EXTREME PROGRAMMING CONCEPTS ........................................................... 129

18. PROGRAMMING TIPS ...................................................................................................................... 131

19. PROGRAMMING IN SPREADSHEET ............................................................................................ 136

20. REFERENCES ..................................................................................................................................... 140

Page 4: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 4 -

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. I tried to explain everything in a way as much easily as possible. However, in many cases, I assumed your prior knowledge of some concept. If you need to know the basic of any language, please consult any book dedicated to that particular language. 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 [email protected] 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!

Page 5: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 5 -

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!

Page 6: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 6 -

2. How to return a single value from a function? 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

/* program to find the area of a rectangle */ #include<stdio.h> int find_area(int l,int w); /* prototype optional in C */ void main(void) { int length, width,area; puts("Enter length"); scanf("%d",&length); puts("Enter width"); scanf("%d",&width); area = find_area(length,width); printf("Area is %d\n",area); } /* the prototype of function is return_type function_name (type argument_1,…, type argument_n) */ int find_area(int l,int w)

Page 7: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 7 -

{ int a; a = l * w; return a; }

The same function is written in Visual BASIC.NET. Code 2-2

Public Function find_area(length, width) as Integer Return length * width End Function

Assume name of the command button is Button1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click l = InputBox("Enter length") w = InputBox("Enter width") area = find_area(l, w) MsgBox ("Area = " & area) End Sub

Universal approach to problem solving – Step 1: Define the problem to be solved. Step 2: Decompose the problem into more easily solved sub-problems. Step 3: Repeat step 2 until the sub-problems can be solved directly. Step 4: Integrate the solutions to solve larger problem.

Page 8: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 8 -

3. How to return multiple values from a function? Remember solution of a quadratic equation? It may have two roots (equal or unequal) or no real root. We shall return two roots of any typical quadratic equation. Study the following C code first. Code 3-1 /* a quadratic equation solver in C */ /* demonstrates returning of multiple values from functions using pointers */ #include <stdio.h> #include <math.h> int solve_quad(int p, int q, int r, float *q1, float *q2); void main(void) { int a,b,c; float root1,root2; int status; puts("Enter a,b,c for ax²+bx+c=0"); scanf("%d,%d,%d",&a,&b,&c); status = solve_quad(a,b,c,&root1,&root2); if(status==1) { puts("The solution is"); printf("%.2f, %.2f\n",root1,root2); printf("Stored at addresses: %x and %x\n", &root1, &root2); } else puts("No real root"); } int solve_quad(int p, int q, int r, float *q1, float *q2) { float determ; determ=q*q-4*p*r; if(determ<0) /* no real root */ { *q1=0; *q2=0;

Page 9: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 9 -

return 0; } else /* real root exists */ { *q1=((-q)+sqrt(determ))/(2*p); *q2=((-q)-sqrt(determ))/(2*p); return 1; } }

As a recapitulation, the basic idea of pointer is as follows: float *q ‘points’ to the float value stored at an address ‘q’. Thus the ‘*’ means ‘contents stored at’. 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

Assume name of the command button is Command1 Dim p As Integer, q As Integer, r As Integer Dim s1 As Single, s2 As Single p = InputBox("Enter a for equation ax²+bx+c=0") q = InputBox("Enter b for equation ax²+bx+c=0") r = InputBox("Enter c for equation ax²+bx+c=0") Call solve_quadratic(ByVal p, ByVal q, ByVal r, s1, s2) MsgBox ("Roots are " & s1 & " and " & s2) End Sub

For a sample run, use following values: a = 1, b = -5, c = 6. The roots are 3 and 2.

Page 10: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 10 -

In VB, the arguments of functions or procedures are always passed by reference by default (up to version 6) and by reference from version 7 (i.e. VB.NET). If you want them to be passed by value, then you must use the keyword ‘ByVal’ in front of each argument that you want to be passed by ‘value’. But in VB.NET, arguments are passed by value by default! Another thing, in VB, the keyword ‘Single’ is equivalent to ‘float’ in C/C++! Don’t forget this! Anyway, it is indeed a good practice in VB to always explicitly write either ByVal or ByRef in function or procedure declaration. 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.*; /* <applet code= "QuadSolverApp" width=160 height=250> </applet> */ public class QuadSolverApp extends JApplet implements ActionListener { JTextField jtfa,jtfb,jtfc,jtfr1,jtfr2; JLabel jlt,jla,jlb,jlc,jlr1,jlr2; JButton jb; public void init() { resize(160,250); Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); // add text fields & lables jlt = new JLabel("Quadratic Equation Solver"); contentPane.add(jlt); jla = new JLabel("Enter a"); contentPane.add(jla);

Page 11: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 11 -

jtfa = new JTextField(8); contentPane.add(jtfa); jlb = new JLabel("Enter b"); contentPane.add(jlb); jtfb = new JTextField(8); contentPane.add(jtfb); jlc = new JLabel("Enter c"); contentPane.add(jlc); jtfc = new JTextField(8); contentPane.add(jtfc); jlr1 = new JLabel("Root 1"); contentPane.add(jlr1); jtfr1 = new JTextField(8); contentPane.add(jtfr1); jlr2 = new JLabel("Root 2"); contentPane.add(jlr2); jtfr2 = new JTextField(8); contentPane.add(jtfr2); // add button JButton jb = new JButton("Solve"); // button label jb.setActionCommand("SolveEquation"); // button action command jb.addActionListener(this); contentPane.add(jb); } public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand()=="SolveEquation") // button action command { // create a new instance of SolveClass SolveClass sc = new SolveClass(); SolveClass sc2; // call Solve method of SolveClass sc2 = sc.Solve(Float.parseFloat(jtfa.getText()),Float.parseFloat(jtfb.getText()),Float.parseFloat(jtfc.getText())); if(sc2.root1==0) { jtfr1.setText("No real root"); jtfr2.setText("No real root"); } else { jtfr1.setText(String.valueOf(sc2.root1));

Page 12: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 12 -

jtfr2.setText(String.valueOf(sc2.root2)); } } } } class SolveClass { static double root1,root2; SolveClass Solve(double a, double b, double c) { double determinant; SolveClass scf = new SolveClass(); 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!

Page 13: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 13 -

What is the difference between a function and a procedure? Consider the following C program. int func (int x) { return x*x; }

It simply returns the square of an integer. Now see the same code written differently. void func (int x, int *y) { *y = x*x; } // value of integer stored at y will be accessible even // outside function because we pass it by reference 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.

Page 14: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 14 -

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

Assume a command button as Command1 in the form. Dim n, Total As Integer n = InputBox("Enter N for 1 + 2 + ... + N") Total = Sum(n) MsgBox ("Sum is " & Total)

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.

Page 15: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 15 -

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)

2

1

3 4

5 6

7 8 9

1011

12

Page 16: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 16 -

Next End Sub

To check the code, you can call it (say inside a button) as TraverseTree(TreeViewName.SelectedNode) 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. Do you now realize the power of recursion? 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.

Page 17: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 17 -

5. Writing DLL in VB.NET 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.) Suppose I often need to solve quadratic equation. So I decided to make it a library function. For this purpose, I thought of including the following code in my own header file “MyFile.h”. 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! So I updated Code 5-1 as Code 5-2 in file MyFile.h.

Page 18: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 18 -

Code 5-2 int solve_quad(int p, int q, int r, float *q1, float *q2) { float determ; determ=q*q-4*p*r; if(determ<0) /* no real root */ { *q1=0; *q2=0; return 0; } else /* real root exists */ { *q1=((-q)+sqrt(determ))/(2*p); *q2=((-q)-sqrt(determ))/(2*p); return 1; } }

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.

Page 19: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 19 -

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. In Windows, all of an application’s code, data, resources and dynamic memory reside within an application’s process. Moreover it is not possible for an application to address data residing outside its own process. Because of this when a DLL is loaded it must somehow reside in the process of the application that loaded the DLL; if more than one application loads the same DLL, it must reside in each application’s process. 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.

Figure 5-1

In this chapter we’ll see how to make a DLL in VB and C/++.

Global Heap

Application 1

Application 2

DLL

Data 1

Data 2

Application code

DLL Code

DLL Data

Application code

DLL Code

DLL Data

Process 1 Process 2

Page 20: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 20 -

To create a very simple DLL in VB.NET, follow the steps as described below. 1. Select File – New Project – Class Library 2. Specify the name of class as ‘MyClass’ 3. Write the following code, change file name as MyClass.vb and compile the

project. The output file will be MyClass.dll. Code 5-3 Public Class SimpleClass Public MyName As String Public Function Sum(ByVal a As Integer, ByVal b As Integer) As Integer Return a + b End Function End Class

4. Open a new Windows Application project say MyClient. 5. Select Project – Add Reference … – browse MyClass.dll file and select it. 6. Add a button to the form and in its click event write following code. 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.

Page 21: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 21 -

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

Page 22: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 22 -

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. Dim a(2, 2), b(2, 2), d(2, 2) As Double Dim m, n As Integer 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 Dim myMath As New CMaths() Dim x = myMath.Product(a, b, d) MsgBox("product") If x <> 0 Then MsgBox("Error") : Exit Sub For m = 0 To 1 For n = 0 To 1 MsgBox("(" & m & "," & n & ")= " & d(m, n)) Next Next

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

Page 23: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 23 -

/* matrix multiplication */ /* example of returning array from a function using pointer */ #include <iostream.h> #include <stdlib.h> int **ProductMatrix(int ** ,int **,int,int,int); 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); } // create rows dynamically matrix1 = new int * [row1]; matrix2 = new int * [row2]; // creates columns dynamically for(i=0;i<row1;i++) matrix1[i] = new int [col1]; for(i=0;i<row2;i++) matrix2[i] = new int [col2]; cout << "Enter the first matrix" << endl; for(i=0;i<row1;i++) { for(j=0;j<col1;j++) { cin >> matrix1[i][j]; } } cout << "Enter the 2nd matrix" << endl; for(i=0;i<row2;i++) { for(j=0;j<col2;j++) {

Page 24: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 24 -

cin >> matrix2[i][j]; } } p = ProductMatrix(matrix1,matrix2,row1,col1,col2); // print product matrix inside main cout << "inside main\n" << endl; for(i=0;i<row1;i++) { for(j=0;j<col2;j++) { cout << p[i][j] << "\t"; } cout << endl; } // 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 int **ProductMatrix(int **m1 ,int **m2,int r1,int c1,int c2) { int i,j,k; int s; int row1,col1,col2; int **matrixp; row1=r1; col2=c2; col1=c1; matrixp = new int * [row1]; for(i=0;i<row1;i++) matrixp[i] = new int [col2]; for(i=0;i<row1;i++) { for(j=0;j<col2;j++)

Page 25: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 25 -

{ 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. The element (3,2) of the matrix may be obtained either by p[3][2] or *(p[3]+2) or *(*(p+3)+2). So when the function returns matrixp, we actually get an array of pointers to pointers of integers!

Page 26: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 26 -

In actual practice, memory is a block of continuous addresses like a list row. 0 1 2 3 p[0] p[1] p[2] p[3]

Figure 5-2

Now I’m giving another useful program in VB.NET. It is solution of simultaneous linear equations by Gauss elimination technique. As I already stated, it will be better if you save the procedure in a class file and later compile it into a DLL. Here’s the main code for solving equations. Code 5-7

Public Function EquationSolve(ByVal A(,) As Double, ByRef x() As Double) As Integer 'This procedure solves a set of linear simultaneous 'equations by Gauss Elimination method 'Usual notation is [A]{X}={B} 'here we combine {-B} into matrix [A] as the last column 'solution column matrix is X 'so for N equations, [A] will have N rows & N+1 columns 'first element of matrix is A(0,0) '[A] is called Augmented Matrix 'Status returns whether solution is successful or not 'returns 0 if successful, non zero if not Dim n, c, i, j, k As Integer Dim AA As Double n = UBound(A, 1) 'rows in augmented matrix ReDim x(n) Try c = A(0, 0) For k = 0 To n - 2 For i = k + 1 To n - 1

Indicates address of this place * ( p [3] + 2 ) indicates value stored at this place

Page 27: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 27 -

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() 'System.Diagnostics.Debug.WriteLine("i=" & i & " j=" & j & " k=" & k & " A(" & i & "," & j & ")=" & A(i, j)) Next j Next i c = A(k + 1, k + 1) Next k 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 Dim B(3, 4) As Double Dim Z(3) As Double Dim W, I As Integer 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

Page 28: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 28 -

B(2, 3) = -1 B(2, 3) = 6 Dim myMath As New CMaths() w = myMath.EquationSolve(b, z) 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. What are Stack and Heap?

Page 29: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 29 -

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.

Page 30: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 30 -

6. Writing DLL in C/C++ 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) First I’ll discuss about console mode DLL. 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

// an example of win32 console DLL #include <math.h> // define what to export from DLL _declspec(dllexport) int SquareIt(int); _declspec(dllexport) double pi = 3.141; _declspec(dllexport)

int solve_quad(int,int,int,float*,float*); // a typical function passed by value int SquareIt(int x) { return x * x; } // a typical function passed by reference int solve_quad(int p, int q, int r, float *q1, float *q2) { float determ; determ=q*q-4*p*r; if(determ<0) { *q1=0; *q2=0; return 0; } else {

Page 31: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 31 -

*q1=((-q)+sqrt(determ))/(2*p); *q2=((-q)-sqrt(determ))/(2*p); return 1; } }

4. Build and compile ExDLL.dll 5. Now open a new ‘Win32 Console Application’ project and name it

ExDLLUse. 6. Add a C++ source code file and write the following code in it. 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> // define what to import from DLL _declspec (dllimport) int SquareIt(int); _declspec (dllimport) double pi; _declspec (dllimport)

int solve_quad(int,int,int,float*,float*); void main(void) { int i; int a,b,c; float root1,root2; int status; // a function called from DLL cout << "Enter an integer " ; cin >> i ; cout << "Square is " << SquareIt(i) << endl; // value of a variable called from DLL cout << "Value of Pi is " << pi << endl; // two values returned from DLL by reference cout << "Enter a,b,c for ax^2+bx+c=0" << endl; cin >> a >> b >> c ; status = solve_quad(a,b,c,&root1,&root2); if(status==1) { cout << "The solution is" << endl; cout << root1 << " and " << root2 << endl;

Page 32: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 32 -

} else cout << "No real root" << endl; }

7. Select Project – Setting – Link tab. 8. In the Object/Library module text box, specify the full path of the dll LIB

file as shown for example (the path will be different in your computer): "D:\C-PROGRAMMING\ExDLL\Debug\ExDLL.lib"

9. Now compile ExDLLUse.exe 10. Now copy the ExDLL.dll file in the same folder where ExDLLUse.exe

exists. 11. Now execute ExDLLUse.exe. It should run as shown below.

D:\TEMP>exdlluse Enter an integer 5 Square is 25 Value of Pi is 3.141 Enter a,b,c for ax^2+bx+c=0 1 -5 6 The solution is 3 and 2

Hooray, you successfully made a DLL in C++! Observe several points. First, in a DLL you must specify which function/variable to be exported using _declspec (dllexport) command. In the same way, you need to tell what to import from DLL to an EXE using _declspec (dllimport) command. In the above example, I showed how to export a variable, a function by value and another function with some values passed by reference. Compare the function with shown in chapter 3. Can I call a DLL written in C from Visual Basic? 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

Page 33: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 33 -

#include <math.h> // to import in VB, you should use _stdcall int _stdcall SquareIt(int); double _stdcall pi = 3.141; int _stdcall solve_quad(int,int,int,float*,float*); // a typical function passed by value int _stdcall SquareIt(int x) { return x * x; } // a typical function passed by reference int _stdcall solve_quad(int p, int q, int r, float *q1, float *q2) { float determ; 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

Page 34: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 34 -

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 Declare Function solve_quad Lib "d:\c-programming\exdll\debug\exdll.dll" _ (ByVal a As Integer, ByVal b As Integer, ByVal c As Integer, _ ByRef r1 As Single, ByRef r2 As Single) 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 status = solve_quad(1, -5, 6, s1, s2) 'try with status = solve_quad(1, 1, 6, s1, s2) If status = 1 Then

Page 35: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 35 -

MsgBox "Root1 " & s1 MsgBox "Root2 " & s2 Else MsgBox "No real root" End If End Sub 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. More general way of writing C/++ DLL 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! To achieve this feat, instead of _dllexport or _stdcall, we need to write BOOL APIENTRY. For example re-write code 6-3 (ExDLL.cpp) as follows. Code 6-7 #include <math.h> #include <windows.h> BOOL APIENTRY SquareIt(int x,int *y) { *y = x * x; return 1; } BOOL APIENTRY solve_quad(int p, int q, int r, float *q1, float *q2) { float determ; 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);

Page 36: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 36 -

return 1; } }

Change code 6-4 (ExDLL.def) slightly as shown below. Code 6-8 LIBRARY ExDLL DESCRIPTION My Test DLL EXPORTS SquareIt solve_quad

Now compile and build the ExDLL.dll file. To use the new DLL in a C/++ executable, change code 6-2 as shown below. Code 6-9 #include <iostream.h> #include <windows.h> // define what to import from DLL _declspec (dllimport) BOOL APIENTRY SquareIt(int,int*); _declspec (dllexport) BOOL APIENTRY solve_quad(int,int,int,float*,float*); void main(void) { int i; int a,b,c,y,z; float root1,root2; int status; cout << "Enter an integer " ; cin >> i ; z = SquareIt(i,&y); cout << "Square is " << y << endl; cout << "Enter a,b,c for ax^2+bx+c=0" << endl; cin >> a >> b >> c ; status = solve_quad(a,b,c,&root1,&root2); if(status==1) { cout << "The solution is" << endl; cout << root1 << " and " << root2 << endl; } else cout << "No real root" << endl;

Page 37: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 37 -

}

Before running, remember to copy the DLL in C/++ exe’s path! To call the DLL from VB, replace code 6-5 by this new code. Code 6-10 Declare Function SquareIt Lib "d:\c-programming\exdll\debug\exdll.dll" _ (ByVal x As Integer, ByRef y As Integer) As Integer Declare Function solve_quad Lib "d:\c-programming\exdll\debug\exdll.dll" _ (ByVal a As Integer, ByVal b As Integer, ByVal c As Integer, _ ByRef r1 As Single, ByRef r2 As Single) As Integer And finally, change code 6-6 as this. Code 6-11 Private Sub Command1_Click() Dim z As Integer Dim y As Integer z = SquareIt(5, y) MsgBox "Square is " & y Dim a As Integer Dim b As Integer Dim c As Integer Dim s1 As Single Dim s2 As Single Dim status As Integer status = solve_quad(1, -5, 6, s1, s2) 'try with status = solve_quad(1, 1, 6, s1, s2) If status = 1 Then MsgBox "Root1 " & s1 MsgBox "Root2 " & s2 Else MsgBox "No real root" End If End Sub

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.

Page 38: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 38 -

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. Can I call any C/++ DLL in this way? 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. Next we’re going to build a MFC DLL! In Visual C++, open a new MFCAppWizard(dll) project and name it as MyDll. The VC will generate lots of code for you. All you need to add your own codes in between. I am showing your own code in blue color and some VC generated code in pink color as a guide where you need to insert your own code. Add the following code in Mydll.h file. Code 6-12 #ifndef __AFXWIN_H__

Page 39: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 39 -

#error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols // 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

Now add the following code in MyDll.cpp file. Code 6-13

///////////////////////////////////////////////////////////////////////////// // The one and only CMyDllApp object CMyDllApp theApp; // my code starts here _declspec(dllexport) void WINAPI ThickRectangle(CDC* pDC, int x1, int y1,int x2, int y2, int t) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); 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(); } _declspec(dllexport) void WINAPI ThickEllipse(CDC* pDC, int x1, int y1, int x2, int y2, int t) {

Page 40: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 40 -

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(); } _declspec(dllexport) void WINAPI ThickPixel(CDC* pDC, int x1, int y1) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); 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. In MyDllExeView.h, add the following code. Code 6-14 #if _MSC_VER >= 1000

Page 41: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 41 -

#pragma once #endif // _MSC_VER >= 1000 // my code starts here extern void WINAPI ThickRectangle(CDC* pDC, int x1, int y1, int x2, int y2,int t); extern void WINAPI ThickEllipse(CDC* pDC, int x1, int y1, int x2, int y2,int t); extern void WINAPI ThickPixel(CDC* pDC, int x1, int y1); // my code ends here class CMyDllExeView : public CView { protected: // create from serialization only

In MyDllExeView.cpp file, add the following code. Code 6-15 void CMyDllExeView::OnDraw(CDC* pDC) { CMyDllExeDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here // my code starts here // call ThickPixel several times for(int i=50;i<900;i++) ThickPixel(pDC,i,75); // 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); pDC->TextOut(50,50,"Saikat's first DLL in Visual C++!"); pDC->MoveTo(200,200); pDC->LineTo(300,300); // my code ends here } ///////////////////////////////////////////////////////////////////////////// // CMyDllExeView diagnostics

Page 42: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 42 -

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++! What is the meaning of _stdcall? 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? Can I use DLL in Unix? Yeah! In Unix, DLLs are known as ‘shared objects’ (*.so) – they work much like in the same way as that of DLLs in Windows. Final notes on DLL – all’s not well that ends well 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

Page 43: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 43 -

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. Create a DLL named ArrayStructure using the methodology described already. The code is given. Code 6-16 #include<string.h> #include<math.h> #include<malloc.h> struct quad { float r1; float r2; char* status; }; quad* _stdcall solve_quad(int *a); quad* _stdcall solve_quad(int *a) { quad *x; x=(quad*)malloc(sizeof(quad)); int p,q,r; float determ; p=*(a+0); q=*(a+1); r=*(a+2); determ=q*q-4*p*r; if(determ<0) /* no real root */ { x->r1=0; x->r2=0;

Page 44: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 44 -

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

Create also the .def file as usual. LIBRARY ArrayStructure EXPORTS solve_quad

Now use the following code to call the function in VB6. Code 6-17 Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _ (Destination As Any, ByVal Source As Any, ByVal Length As Long) Private Declare Function solve_quad Lib "arraystructure.dll" _ (ByVal m As Long) As Long Private Sub Command1_Click() Dim adr As Long Dim z(3) As Long Dim Root1 As Single Dim Root2 As Single Dim Solution As String 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

Page 45: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 45 -

Execute the VB6 program and you’ll see two roots and status of solution. I understand that code 6-17 requires some clarification. VarPtr is an undocumented V6B function that returns the address of a variable as long. Two similar functions are StrPtr and ObjPtr. In code 17-16, we pass the matrix as the address of its first element i.e. a(0). The quad* indicates that the function solve_quad returns an address which holds a data of type quad. In C/++, an int needs 4 bytes. In VB6, a long needs the same amount of bytes. That’s why we defined z(3) as Long in VB6 instead of Integer. (You may wonder why there is such a discrepancy between C and VB6 data types. Well, it is a logical question. However, this has been rectified in VB.NET where Integer takes 4 bytes as that of in C and Short takes 2 bytes as of earlier Integer!) 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!

Page 46: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 46 -

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

Page 47: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 47 -

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"); printf("Enter your choice\n"); fflush(stdin); scanf("%d",&choice); 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)

Page 48: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 48 -

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

Page 49: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 49 -

fclose(fp); fclose(ft); remove("data.dat"); rename("temp.dat","data.dat"); fp=fopen("data.dat","rb+"); printf("Delete another record 1 for yes\n"); fflush(stdin); scanf("%d",&another); } break; 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.

Page 50: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 50 -

Code 7-2

REM database handling, structure and file example in QBASIC REM (c) Saikat Basak REM with add, display, search, modify, delete in binary mode ON ERROR GOTO 100 TYPE person myname AS STRING * 30 myaddress AS STRING * 40 myphone AS STRING * 10 END TYPE DIM MyBook AS person DIM whatname AS STRING * 30 DIM deletename AS STRING * 30 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 SELECT CASE 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"

Page 51: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 51 -

INPUT "Enter name: "; MyBook.myname INPUT "Enter address: "; MyBook.myaddress INPUT "Enter phone#: "; MyBook.myphone PUT #1, i, MyBook i = i + 80 INPUT "Add another ? ", another$ LOOP CLOSE #1 OPEN "database.idx" FOR OUTPUT AS #10 PRINT #10, i CLOSE #10 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"

Page 52: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 52 -

INPUT "Press any key to continue", x 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 SHELL "del database.dat" SHELL "ren temp.dat database.dat" OPEN "database.idx" FOR OUTPUT AS #10 PRINT #10, q - 80 CLOSE #10 INPUT "Press any key to continue", x 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

Page 53: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 53 -

IF flag = 0 THEN PRINT "Not found" INPUT "Press any key to continue", x 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? Assuming you name the file as DATABASE.BAS, it is necessary that before running this program, you create a text file named DATABASE.IDX with just the number 1 written in it. You can use the above code in VB with just slight modifications! Exercise 7-1

Page 54: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 54 -

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!

Page 55: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 55 -

8. Pointer paradoxes in C If you ask programmers what is the most confusing thing in C programming, I’m sure that they will say ‘pointers’! Indeed pointers are difficult to master at the beginning. In fact, many programmers hate C because of pointers. Surprisingly to placate them modern programming languages such as Visual Basic, Java etc. removed explicit pointer feature. (Though they handle internally everything using pointers!) 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> int solve_quad(int p, int q, int r, float &q1, float &q2); void main(void) { int a,b,c; float root1,root2; int status; cout << "Enter a,b,c for ax²+bx+c=0" << endl; cin >> a >> b >> c; status = solve_quad(a,b,c,root1,root2); if(status==1) { cout << "The solution is" << endl; cout << root1 << " " << root2 << endl; } else cout << "No real root" << endl; } int solve_quad(int p, int q, int r, float &q1, float &q2) { float determ;

Page 56: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 56 -

determ=q*q-4*p*r; if(determ<0) /* no real root */ { q1=0; q2=0; return 0; } else /* real root exists */ { q1=((-q)+sqrt(determ))/(2*p); q2=((-q)-sqrt(determ))/(2*p); return 1; } }

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. So we can summarize the C/++ function calling syntax in following table. Code element By value (C/++) By pointer (C/++) By reference

(C++ only) Function call Var &Var Var Function prototype

Var *Var &Var

Function body Var *Var Var 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.

Page 57: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 57 -

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 swap(void **x, void **y); template <class T>void swap_t(T& x, T& y); 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; }

Page 58: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 58 -

void swap(void **x,void **y) { void *temp; temp = *x; *x = *y; *y = temp; } template <class T> void swap_t(T& x, T& y) { T temp; temp=x; x=y; y=temp; }

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.

Page 59: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 59 -

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? typedef struct employee { int empid; char name[20]; struct employee *next; } emp;

It means employee is a structure. It holds one integer, one character array of length 20 and an address next, which stores another employee data type. This type of structure is called “Self Referential Structure” because at least one element of this structure contains an address, which stores same structure data type. If you still find the explanation garbled then read the explanation of void pointer again. Using self-referential structure, we can write linked list, binary search tree and many other data structures! 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> typedef struct employee { int empid; char name[20]; struct employee *next; } emp; /* 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)

Page 60: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 60 -

{ int choice; employee *p=NULL; printf("Enter your choice\n"); printf("1. Create link list\n"); printf("2. Display link list\n"); printf("3. Search an item in list\n"); printf("4. Delete an item from list\n"); 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); printf("Enter your choice\n"); printf("1. Create link list\n"); printf("2. Display link list\n"); printf("3. Search an item in list\n"); printf("4. Delete an item from list\n"); scanf("%d",&choice); } while(choice ==1 || choice==2 || choice==3 || choice==4); } /* create link list */ emp *create(struct employee *ptr) { emp *first=ptr; emp *curr; int EmployeeId; char EmployeeName[20]; printf("Enter employee number\n"); scanf("%d",&EmployeeId); printf("Enter name\n"); fflush(stdin); scanf("%[^\n]s",EmployeeName); if(ptr==NULL) // no item so far

Page 61: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 61 -

{ curr=(emp*)malloc(sizeof(emp)); first=curr; curr->empid=EmployeeId; strcpy(curr->name,EmployeeName); curr->next=NULL; return first; } curr=ptr; while(curr->next!=NULL) // traverse entire list to find out last item curr=curr->next; curr->next=(emp*)malloc(sizeof(emp)); curr->next->empid=EmployeeId; strcpy(curr->next->name,EmployeeName); curr->next->next=NULL; return first; // returns beginning address of list } /* display entire link list */ void display(struct employee *ptr) { while(ptr!=NULL) { printf("%d\t",ptr->empid); printf("%s\n",ptr->name); ptr=ptr->next; } } /* search link list */ void search(struct employee *ptr) { int empnum; emp *ser=ptr; /* assigning beginning address of the list */ printf("Enter employee number to search\n"); scanf("%d",&empnum); do

Page 62: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 62 -

{ if(ser->empid==empnum) { printf("%s\n",ser->name); return; } ser=ser->next; } while(ser!=NULL); /* this point will be reached if no match found */ if(ser==NULL) { printf("No match\n"); } } /* delete an item form list */ void erase(struct employee *ptr) { int empnum; int flag=0; emp *old; emp *temp=ptr; /* equivalent of emp *temp = ptr and then temp = ptr */ printf("Enter employee number to delete\n"); scanf("%d",&empnum); while(temp!=NULL) // traverse list until last item { if(temp->empid==empnum) // item found { if(temp==ptr) // item to be deleted is first item { ptr=temp->next; printf("Deleted\n"); flag=1; return; } else { old->next=temp->next; // item other than first printf("Deleted\n"); flag=1; return; }

Page 63: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 63 -

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

Page 64: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 64 -

9. String handling in C++ 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;

Page 65: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 65 -

LongText = "A quick brown fox jumped over the lazy dogs."; cout << "LongText = " << LongText << endl; cout << "fox was found at position " << LongText.find("fox") << endl; // venture other find functions eg. rfind, find_first_of, find_last_of, // find_first_not_of, find_last_not_of, erase etc. // replace string FindWhat = "fox"; int PositionOfFindWhat = LongText.find("fox"); int LengthOfFindWhat = FindWhat.length(); cout << "fox replaced with lion ->" << LongText.replace(PositionOfFindWhat,LengthOfFindWhat,"lion") << 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!

The reasonable man adapts himself to the world.The unreasonable man persists in trying to adaptthe world to him. Therefore, all progressesdepend on the unreasonable man.

Page 66: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 66 -

10. Function Overloading 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 // function overloading demo #include <iostream.h> 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; } int volume(int l,int w,int h) { int v; v = l * h * w; return v; } 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. But VB.NET you can do it in same way! Code 10-2

Page 67: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 67 -

Public Function FindVolume(ByVal l As Integer, ByVal w As Integer, ByVal h As Integer) As Integer Return l * w * h End Function Public Function FindVolume(ByVal l As Single) As Single Return l * l * l End Function

And call them as shown below. MsgBox(FindVolume(2, 3, 4)) MsgBox(FindVolume(5.25))

Function overloading feature can even be used in Oracle’s functions and procedures.

Yawn!

Page 68: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 68 -

11. Object Oriented Programming System (OOPS) The basic concept of data hiding is shown in figure 7-1. CLASS

Figure 11-1

For OOPS, you need to know the following concepts. 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. We shall discuss various aspects of Object Oriented Programming throughout this book!

Data

Functions

Data

Functions

Private Area No Entry

Public Area Entry Allowed

Page 69: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 69 -

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. Different programs handle object-oriented concept differently. Here, I shall show you a program in C++, which incorporates a number of OOP concepts. 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! Well, enough talking, study the following C++ code. Code 11-1

// demonstration of Object Oriented features of C++ // a car building program #include <iostream.h> #include <string.h> // define engine components struct engine { float displacement_L; float Power_kW; int cylinder; char fuel[7]; int valve; char transmission[10]; };

Page 70: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 70 -

// define class Car class Car { private: int wheels; int doors; engine e; char brake[5]; char color[10]; public: void MakeDoor(int); void FitWheels(int); void InstallEngine(struct engine); void FitBrake(char[]); void PaintBody(char[]); }; // Truck extends Car class Truck:public Car { private: float LoadSpace; public: void FitLoader(float); }; // Bird is something which can fly by flapping wings class Bird { private: float WingSpan_m; public: void MakeWing(float); void Fly(void); }; // Aeroplane extends from Car and Bird // ie it has doors, wheels, engine etc. and it can fly // like bird, the flying method is different from that // of a bird class Aeroplane: public Car, public Bird { public: void Fly(int); }; // now define the functions for Car

Page 71: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 71 -

void Car::MakeDoor(int door) { doors = door; cout << doors << " doors" << endl; } void Car::FitWheels(int wheel) { wheels = wheel; cout << wheels << " wheels" << endl; } 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; } void Car::FitBrake(char g[]) { strcpy(brake, g); cout << brake << " brake" << endl; } void Car::PaintBody(char b[]) { strcpy(color,b); cout << color << " color" << endl; } // now define the functions exclusive for Truck

Page 72: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 72 -

void Truck::FitLoader(float LoadVolume) { LoadSpace = LoadVolume; cout << LoadVolume << " cubic meter payload" << endl; } // function for bird void Bird::MakeWing(float wingspan) { WingSpan_m = wingspan; cout << WingSpan_m << " wing span" << endl; } // birds fly by flapping wings void Bird::Fly(void) { cout << "Bird is flying by flapping wings..." << endl; } // function for Aeroplane // aeroplane's complicated Fly should override bird's Fly method void Aeroplane::Fly(int speed) { cout << "starting engine..." << endl; cout << "taxing..." << endl; cout << "taking off..." << endl; cout << "Flying aeroplane at speed of " << speed << " km/h. Whoosh..." << endl; } // main function begins here 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;

Page 73: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 73 -

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"); cout << "Car is ready. Have a safe driving..." << endl; // now make a truck cout << "Now we are making a Truck..." << endl; cout << "Assmebling MyTruck..." << endl; // create Truck object Truck MyTruck; // assemble the truck // attach door MyTruck.MakeDoor(2); // fit wheels MyTruck.FitWheels(6); // engine specification engine te; te.displacement_L=6; te.Power_kW=250; te.cylinder=8; strcpy(te.fuel,"diesel"); te.valve=16; strcpy(te.transmission,"manual"); // assemble engine MyTruck.InstallEngine(te); // assemble Load Space MyTruck.FitLoader(100); // fit brake MyTruck.FitBrake("drum"); cout << "The truck is ready... Do you want to carry your car?" << endl; // create the aeroplane Aeroplane MyPlane; // fly the plane MyPlane.Fly(300); } // end of main function // end of source code

The output of the above program will be as shown below.

Page 74: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 74 -

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. I am providing the equivalent Java code here. 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;

Page 75: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 75 -

private float displacement_L; private float Power_kW; private int cylinder; private String fuel; private int valve; private String transmission; private String brake; private String color; public void MakeDoor(int door) { doors = door; System.out.println("doors = " +doors); } public void FitWheels(int wheel) { wheels = wheel; System.out.println("wheels = " +wheels); } public void InstallEngine(float displacement, float power, int cylinderno, String fueltype,int valveno, String transmissiontype) { displacement_L = displacement; System.out.println("displacement is " +displacement_L); Power_kW = power; System.out.println("Power is " +Power_kW); cylinder = cylinderno; System.out.println("Cylinder " +cylinder); fuel = fueltype; System.out.println("fuel " +fuel); valve = valveno; System.out.println("valve " +valve); transmission = transmissiontype; System.out.println("transmission " +transmission); } public void FitBrake(String braketype) { brake = braketype; System.out.println("brake = " +brake); } public void PaintBody(String paintcolor) { color = paintcolor; System.out.println("color = " +color);

Page 76: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 76 -

} } // 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 Truck MyTruck = new 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).

Page 77: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com

Code 11-3 Namespace Vehicle Public Class C Inherits S Private wh Private do Private br Private co Public Str Public Public Public Public Public Public End Struct Private Ve Public Sub MyBase 'This Initia ' TODOcall End Sub Public Sub wheels MsgBox"Vehicle") End Sub Public Sub doors MsgBox End Sub Public Sub brake MsgBox"Vehicle") End Sub

It is a common sense to take amethod and try it. If it fails, admit itfrankly and try another. But aboveall, try something.

- 77 -

Vehicle ystem.ComponentModel.Component

eels As Integer ors As Integer ake As String lor As String

ucture Engine displacement_L As Single power_kW As Single cylinder As Integer fuel As String valve As Integer transmission As String ure

hicleEngine As Engine

New() .New()

call is required by the Component Designer. lizeComponent()

: Add any initialization after the InitializeComponent()

FitWheels(ByVal wheel As Integer) = wheel ("wheels = " & wheels, MsgBoxStyle.Information,

MakeDoor(ByVal door As Integer) = door ("Doors = " & door, MsgBoxStyle.Information, "Vehicle")

FitBrake(ByVal BrakeType As String) = BrakeType ("Brake type = " & brake, MsgBoxStyle.Information,

Page 78: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 78 -

Public Sub PaintBody(ByVal MyColor As String) color = MyColor MsgBox("Color = " & color, MsgBoxStyle.Information, "Vehicle") End Sub Public Sub InstallEngine(ByRef EngineData As Engine) VehicleEngine.displacement_L = EngineData.displacement_L VehicleEngine.power_kW = EngineData.power_kW MsgBox("Displacement " & VehicleEngine.displacement_L & " L", MsgBoxStyle.Information, "Vehicle") MsgBox("Power " & VehicleEngine.power_kW & " kW", MsgBoxStyle.Information, "Vehicle") VehicleEngine.cylinder = EngineData.cylinder MsgBox("Cylinder " & VehicleEngine.cylinder, MsgBoxStyle.Information, "Vehicle") VehicleEngine.fuel = EngineData.fuel MsgBox("Fuel is " & VehicleEngine.fuel, MsgBoxStyle.Information, "Vehicle") VehicleEngine.valve = EngineData.valve MsgBox("Valve " & VehicleEngine.valve, MsgBoxStyle.Information, "Vehicle") VehicleEngine.transmission = EngineData.transmission MsgBox("Transmission is " & VehicleEngine.transmission, MsgBoxStyle.Information, "Vehicle") End Sub #Region " Component Designer generated code " 'Required by the Component Designer Private components As Container 'NOTE: The following procedure is required by the Component Designer 'It can be modified using the Component Designer. 'Do not modify it using the code editor. Private Sub InitializeComponent() components = New System.ComponentModel.Container() End Sub #End Region End Class Public Class CCar Inherits CVehicle End Class Public Class CTruck Inherits CVehicle Private LoaderVol As Single Public Sub FitLoader(ByVal LoaderVolume As Single) LoaderVol = LoaderVolume MsgBox("Loader Volume = " & LoaderVol, MsgBoxStyle.Information, "Truck") End Sub End Class End Namespace

Page 79: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 79 -

To use it in a client project, you can call it in following way. Private Sub cmdMakeCar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdMakeCar.Click Dim MyCar As New VehicleClass.Vehicle.CTruck() MyCar.FitWheels(4) MyCar.MakeDoor(4) MyCar.FitBrake("disc") Dim MyEngine As VehicleClass.Vehicle.CCar.Engine 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 Private Sub cmdMakeTruck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdMakeTruck.Click Dim MyTruck As New VehicleClass.Vehicle.CTruck() MyTruck.FitLoader(100) End Sub

So, mind boggling, eh? Have fun!

Page 80: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 80 -

Comparison of OOPS features Table 11-1

Feature C++ Java 1.2 VB.NET Class Yes Yes Yes Object Yes Yes Yes Simple Inheritance Yes Yes Yes * Multiple Inheritance Yes No No Interface No (though

abstract class is there)

Yes Yes

Function overloading Yes Yes Yes * Function overriding Yes Yes Yes * Polymorphism Yes Yes Yes (through

interface) Passing object as function argument

Yes Yes Yes

Pointer Yes No No Constructor Yes Yes Yes * Nested/inner class Yes Yes No Optional/default arguments in function

Yes No Yes

Structure Yes No (emcompassed in class)

Yes (User defined type)

Friend function Yes No Yes String data type No (in C++, it

is available as class)

Yes (actually String is a class in Java)

Yes

Template function/class

Yes No No

* Indicates feature either unavailable in earlier versions or was implemented differently. For example, simple inheritance was supported in VB5 onwards though you needed to write function/procedure bodies yourself in derived classes.

Page 81: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 81 -

12. The world of Distributed Computing – COM and CORBA 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. Fortunately most recent programming languages and applications as well support COM. All the COM objects are complete by themselves. You can just add them in your required program and it should provide its service! It is not necessary that only DLLs or OCXs are COMs. Even EXEs can be COMs. From OLE to 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.

Page 82: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 82 -

The internal architecture of COM Interfaces are everything in COM! For COM, an interface is a specific memory structure containing an array of function pointers. Each array element contains the address of a function implemented by the component. To be precise, COM states what a block of memory must look like to be considered an interface. You may note that, the memory layout of a COM interface is the same as that of C++ compiler generates for an abstract base class. 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 ; }

Figure 12-1

The ‘Virtual Function Table’ is an array of pointers that point to the implementations of the virtual functions. For example, the first entry in above vtbl contains the address of function Fx1 as it is implemented in the derived class. 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.

pIX

Virtual Function Table (vtbl) contains pointers to member functions

Vtbl pointer &Fx1&Fx2&Fx3&Fx4

Virtual Function Table (vtbl)

IX

Page 83: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 83 -

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.

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.

pIX

Virtual Function Table (vtbl) contains pointers to member functions

Vtbl pointer QueryInterface

AddRef

Release

Fx

Virtual Function Table (vtbl)

IX

QueryInterface

AddRef

Release

Fx

CA Client

Page 84: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 84 -

How do I write COM? Anything you write in VB is automatically COM (Whew)! Anything written in Visual C++ will also be COM if you tell them to be! To make your life easier (or difficult), Microsoft uses an utility called Active Template Library (ATL) in its Visual Studio. ATL helps you to write COM objects from scratch. You can also write COMs using wizard in MFC. ATL is a lightweight library of templates designed to make it easy to build small, fast ActiveX controls. Since ATL is implemented as a set of templates, there is very little runtime overhead for interface queries and passing. But using ATL is quite difficult (really). ATL is not intended to be general-purpose solution for writing any kind of programs. ATL is optimized for use with COM. 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. DCOM provides network transparency and communication automation so that communications can take place between objects without one object needing to be aware of another object's location. The objects can be in different processes on the same machine, or in separate processes on different machines.

Page 85: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 85 -

What is CORBA? CORBA means ‘Common Object Request Broker Architecture’. It is similar to COM (strictly speaking it is more similar to DCOM). COM is Microsoft's technology where as CORBA is Sun's technology. Though I said they are similar their internal architecture is quite different. Detail discussion of CORBA is beyond the scope of this book. If you are interested in details, please consult books dedicated on these topics.

Figure 12-3

The IDL interface definitions inform clients of an object offering an interface exactly what operations an object supports, the types of their parameters and what return type to expect. A client programmer needs only the IDL to write client code that is ready to invoke operations on a remote object. The client uses the data type defined in IDL though a language mapping. The mapping defines the programming language constructs (data types, classes etc.) that will be generated by the IDL compiler supplied by an ORB vendor. 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

Client

Client Proxy (Stub Code)

Object Request Broker

Skeleton Code

Object Implementation

Page 86: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 86 -

skeleton. In this way object method implementation can be invoked and the results returned by the same means. Summary of CORBA development process. 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.

Page 87: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 87 -

Sample ATL COM/DCOM project 1. In Visual C++, open a new ATL project named ATLquadratic. 2. In step 1 of 1, select type as EXE. 3. Right clicking on ATLquadratic classes, create a New ATL Object… 4. Choose ‘Simple Object’ and give short name ‘Quad’. (In ATL Object

Wizard Properties dialog box) 5. By right clicking on ‘IQuad’ on class view, add a new method. 6. The ‘Add Method to Interface’ dialog box opens. 7. Specify method name as ‘solve_quad’. 8. Write parameters as [in] int a, [in] int b, [in] int c, [out]

double *root1, [out] double *root2,[out,retval] double *result

9. Expand ‘CQuad’ class in Class View and then ‘IQuad’ interface. By double clicking on ‘solve_quad’ method, open up ‘Quad.cpp’ source code file.

10. Add the following code. Visual C++ generated code is shown pink. Code 12-1

// Quad.cpp : Implementation of CQuad #include "stdafx.h" #include "ATLquadratic.h" #include "Quad.h" #include <math.h> ///////////////////////////////////////////////////////////////////////////// // CQuad // return *result must be last parameter STDMETHODIMP CQuad::solve_quad(int a, int b, int c, double * root1, double * root2,double * result) { // TODO: Add your implementation code here double determ; determ = b*b - 4*a*c; if(determ<0) return E_INVALIDARG; *root1=((-b)+sqrt(determ))/(2*a); *root2=((-b)-sqrt(determ))/(2*a); *result = 1; return S_OK; }

11. Now compile the code.

Page 88: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 88 -

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

Page 89: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 89 -

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 the definition of COM? COM is a specification for building software components that can be assembled into new programs or add functionality to existing programs. COM components can be written in a variety of computer languages and can be updated and reinstalled without requiring changes to other parts of the program. 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!

Figure 12-4 When you call a function/procedure on a COM component that is running in a separate process, COM handles inter-process communication by packaging the parameter data and passing it across process boundary. This is called ‘Marshalling’. Suppose you want to pass a parameter by reference. COM passes it by value (by making a copy) at first to the called procedure. Once this

PROCESS A

PROCESS B

COM copies data from process A to B

Data is changed inside process B

Modified data is again copied to same address space in Process A

Page 90: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 90 -

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. Why do I sometimes get “ActiveX can’t create Object” error message in VB applications? This is most commonly due to version incompatibility. Select Project – Properties – Component tab – Binary Compatibility option while compiling your ActiveX application in VB. Also specify the file name as well. From COM to CLR – what the hype all about? 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.) However, this concept of intermediate code before machine language executable is not entirely new. VB has always included compiling to p-code option from the very beginning. Programs compiled with p-code are usually 50% smaller in size compared to that of native code. But like Java, p-code executes around 10 times slower than native code! The term p-code originates

Page 91: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 91 -

form ‘pseudo-code’, which is an intermediate step between high level instructions in your VB program and low level native code executed by your computer’s processor. At runtime, VB translates each p-code statement to native code. If Microsoft ever develops VB virtual machine for p-code in different platforms then VB will be just as portable (i.e. platform independent) as that of Java! 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.

One machine can do the work of fiftyordinary men. No machine can do thework of one extra ordinary man.

Page 92: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 92 -

13. Database connectivity 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. Microsoft’s latest invention on database connection is ADO (ActiveX Data Object). The functionality of ADO is represented schematically by the following diagram.

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.

.NET front end client ADO OLE DB Database

Page 93: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 93 -

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. The VB.NET front-end form mainly can be of following types:

1. Single record format – only master table data 2. Multi record (grid) format – only one table (master) 3. Single record master and multi record (grid) detail 4. Multi record master (grid) and multi record detail (grid) 5. More than one level of master detail data (single record format multiple

grids) 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. Multi record VB.NET form 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.) Figure 13-2 shows how the form looks like. Create a similar looking form – the menu names will be obvious from code listing. Name of the form is frmUserDefinedQuery.

Page 94: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 94 -

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. Concentrate on these functions/procedures – ShowSqlResultInDatagrid, code inside mnuQueryConnect, mnuQueryExecute and mnuQueryUpdate. Observe how different connection string has been used for different databases.

Figure 13-2

The following code is written inside this form. Code 13-1

Imports System.Data Imports System.Data.OleDb Public Class frmUserDefinedQuery Inherits System.Windows.Forms.Form [Windows Form Designer code] has been omitted for brievity Dim connstr As String Dim cnn As System.Data.OleDb.OleDbConnection Dim da As OleDbDataAdapter Dim ds As DataSet Dim cmdBld As OleDbCommandBuilder Public Function ShowSqlResultInDatagrid(ByVal ConnectionDetail As String, ByVal SqlText As String, ByVal DataGridName As DataGrid) As Integer '0 return means success Try

Page 95: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 95 -

da = New OleDbDataAdapter(SqlText, connstr) cmdBld = New OleDbCommandBuilder(da) 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 Private Sub frmUserDefinedQuery_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load dg.CaptionVisible = False cboDbtype.Items.Add("Access") cboDbtype.Items.Add("Oracle") cboDbtype.Items.Add("SQL Server") End Sub Private Sub mnuQueryConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuQueryConnect.Click Dim db As String db = cboDbtype.Text If db = "Access" Then 'connect with Access connstr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & txtDatabase.Text & ";" ElseIf db = "Oracle" Then 'connect with Oracle connstr = "Provider=MSDAORA.1;Password=" & txtPwd.Text & ";User ID=" & txtUser.Text & ";Data Source=" & txtDatabase.Text ElseIf db = "SQL Server" Then 'connect with SQL Server connstr = "Provider=SQLOLEDB.1;User ID=" & txtUser.Text & ";Pwd=" & txtPwd.Text & ";Initial Catalog=" & txtDatabase.Text & ";Data Source=" & txtServer.Text & ";" Else MessageBox.Show("Invalid database type!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End If Try cnn = New System.Data.OleDb.OleDbConnection(connstr) stbStatus.Text = "Connecting with database..." cnn.Open() stbStatus.Text = "Connection successful."

Page 96: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 96 -

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 Private Sub cboDbtype_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboDbtype.SelectedIndexChanged If cboDbtype.Text = "Access" Then 'ask user to select Access file Dim AccessFile As String OpenFileDialog1.Filter = "Access Files|*.mdb" OpenFileDialog1.ShowDialog() AccessFile = OpenFileDialog1.FileName If AccessFile = "" Then Exit Sub txtDatabase.Text = AccessFile txtUser.Text = "Admin" End If End Sub Private Sub mnuQueryExecute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuQueryExecute.Click If txtQuery.Text = "" Then MessageBox.Show("Please specify query", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If 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 Private Sub mnuQueryUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuQueryUpdate.Click Try 'update data source da.Update(ds, "UserDefinedQuery") MessageBox.Show("Dataset Updated", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Catch x As Exception MessageBox.Show(x.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub End Class

Page 97: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 97 -

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. Master detail VB.NET form 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. It is assumed that we are connecting to an Oracle database as mkm/mkm@mdb. The tables we are going to use are – product (master) and price (detail). Not all columns of the table will be used in the example.

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

Page 98: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 98 -

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 Public Class frmProductPrice Inherits System.Windows.Forms.Form [Windows Form Designer code] has been omitted for brievity #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 sql As String = "SELECT * FROM PRODUCT" Dim da As OleDbDataAdapter = New OleDbDataAdapter(sql, Conn) Dim cmdBld As OleDbCommandBuilder = New OleDbCommandBuilder(da) 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 Private Sub FillDataSetAndView() ds = New DataSet() da.Fill(ds, "Product") 'change table name as required dv = New DataView(ds.Tables("Product")) 'change table name as required cm = CType(Me.BindingContext(dv), 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

Page 99: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 99 -

'*************************************************************** Dim dtProduct, dtPrice As DataTable dtProduct = ds.Tables("Product") dtPrice = ds.Tables("Price") Dim dcParent, dcChild As DataColumn dcParent = ds.Tables("Product").Columns("ProdCode") dcChild = ds.Tables("Price").Columns("ProdCode") dr = New DataRelation("ProductPrice", dcParent, dcChild) ds.Relations.Add(dr) '*************************************************************** 'for detail part '*************************************************************** dgD.CaptionText = "Price" 'bind datagrid with dataset dgD.SetDataBinding(ds, "Price") 'change table name as required ShowDetail() End Sub #End Region #Region "Generic common code - no customization required " '*************************************************************** 'generic common code '*************************************************************** Private Sub ShowPosition() Try Dim msg As String msg = "Record " & cm.Position + 1 & " of " & cm.Count() stbStatus.Panels(1).Text = msg Catch x As System.Exception MessageBox.Show(x.ToString) End Try End Sub Private Sub NextRecord() cm.Position += 1 ShowPosition() ShowNonBaseTableFields() End Sub Private Sub PreviousRecord() cm.Position -= 1 ShowPosition() ShowNonBaseTableFields() End Sub Private Sub LastRecord() cm.Position = cm.Count - 1 ShowPosition() ShowNonBaseTableFields() End Sub Private Sub FirstRecord() cm.Position = 0 ShowPosition() ShowNonBaseTableFields() End Sub

Page 100: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 100 -

Public Sub FormLoad() FillDataSetAndView() BindFields() ShowPosition() ShowNonBaseTableFields() End Sub Public Sub NewRecord(ByVal InsertSql As String) Dim intPosition As Integer Dim objCommand As OleDbCommand = New OleDbCommand() 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 Private Sub UpdateRecord(ByVal UpdateSql As String) Dim intPosition As Integer Dim objCommand As OleDbCommand = New OleDbCommand() 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

Page 101: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 101 -

Conn.Close() End Try FillDataSetAndView() BindFields() cm.Position = intPosition ShowPosition() End Sub Private Sub DeleteRecord(ByVal DeleteSql As String) Dim intPosition As Integer Dim objCommand As OleDbCommand = New OleDbCommand() 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()

Page 102: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 102 -

txtProdCode.DataBindings.Add("Text", dv, "ProdCode") txtProdName.DataBindings.Add("Text", dv, "ProdName") txtCategory.DataBindings.Add("Text", dv, "Category") End Sub Public Sub ShowNonBaseTableFields() 'write code Try Conn.Open() Dim cmd1 As New System.Data.OleDb.OleDbCommand("ShowCategoryDescription", Conn) cmd1.CommandType = CommandType.StoredProcedure Dim p1, p2 As OleDb.OleDbParameter p1 = New OleDb.OleDbParameter("@piCatNo", OleDbType.Integer) p1.Direction = ParameterDirection.Input p1.Value = txtCategory.Text p2 = New OleDb.OleDbParameter("@poCatDesc", OleDbType.VarChar, 200) p2.Direction = ParameterDirection.Output cmd1.Parameters.Add(p1) cmd1.Parameters.Add(p2) cmd1.ExecuteNonQuery() txtCategoryDesc.Text = p2.Value Catch z As Exception MessageBox.Show(z.ToString, z.Message, MessageBoxButtons.OK, MessageBoxIcon.Error) 'txtCategoryDesc.Text = "N/A" Finally Conn.Close() End Try End Sub Public Sub SaveRecords() Try da.Update(ds, "Product") daD.Update(ds, "Price") MessageBox.Show("Record(s) Updated!", "Record Save", MessageBoxButtons.OK, MessageBoxIcon.Information) Catch x As Exception MessageBox.Show(x.Message, "Record Save", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Private Sub ShowDetail() dvD.RowFilter = "PRODCODE='" & txtProdCode.Text & "'" dgD.DataSource = dvD End Sub Private Sub FormatDataGrid() '*************************************************************** 'for formatting data grid '*************************************************************** Dim GTS As New DataGridTableStyle() GTS.MappingName = "Price" 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

Page 103: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 103 -

GTS.HeaderForeColor = System.Drawing.Color.White Dim dgcProdCode As New DataGridTextBoxColumn() Dim dgcStartDate As New DataGridTextBoxColumn() Dim dgcEndDate As New DataGridTextBoxColumn() Dim dgcBuyPrice As New DataGridTextBoxColumn() Dim dgcSellPrice As New DataGridTextBoxColumn() 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 '***************************************************************

Page 104: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 104 -

Private Sub frmProductPrice_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load FormatDataGrid() End Sub Private Sub mnuNavigateFirst_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuNavigateFirst.Click FirstRecord() End Sub Private Sub mnuNavigatePrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuNavigatePrevious.Click PreviousRecord() End Sub Private Sub mnuNavigateNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuNavigateNext.Click NextRecord() End Sub Private Sub mnuNavigateLast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuNavigateLast.Click LastRecord() End Sub Private Sub mnuRecordInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRecordInsert.Click NewRecord("INSERT INTO PRODUCT(PRODCODE,PRODNAME,CATEGORY) VALUES('" & txtProdCode.Text & "','" & txtProdName.Text & "','" & txtCategory.Text & "')") End Sub Private Sub mnuRecordUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRecordUpdate.Click 'UpdateRecord("UPDATE PRODUCT SET PRODNAME = '" & txtProdName.Text & "', CATEGORY='" & txtCategory.Text & "' WHERE PRODCODE = '" & txtProdCode.Text & "'") SaveRecords() End Sub Private Sub mnuRecordDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRecordDelete.Click DeleteRecord("DELETE FROM PRODUCT WHERE PRODCODE = '" & txtProdCode.Text & "'") End Sub Private Sub mnuFileClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFileClose.Click Me.Close() End Sub Private Sub txtProdCode_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtProdCode.TextChanged ShowDetail() End Sub Private Sub mnuFileLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFileLoad.Click FormLoad() End Sub

Page 105: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 105 -

End Class Well, what’s the problem? 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.

CREATE OR REPLACE PROCEDURE ShowCategoryDescription ( piCatNo IN NUMBER, poCatDesc OUT VARCHAR2 ) AS BEGIN SELECT G.DESCRIPTION INTO poCatDesc FROM CATEGORY G WHERE G.CATEGORYNO = piCatNo; EXCEPTION WHEN OTHERS THEN poCatDesc := 'N/A'; END;

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.

Page 106: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 106 -

Can you explain a little bit how to implement 3-tier architecture using ADO and COM? Definitely! Take the example of a CARS table. Suppose we want to increase price of all cars by 10%. Assume that we shall keep this 'business logic' in middle tier. 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. 1. Open the connection with database 2. Open a client side ADO record set 3. Disconnect the database 4. Write code in ADO syntax to update the ADO record set that is fetched in step 2 above i.e. you first update the records on client side record set 5. Make connection with database again 6. Save the changes made to client side record set into the database using batch update method 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. How do I call Stored Procedures from VB6? 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

Page 107: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 107 -

return 0; end MySP; create or replace procedure MySP1(x in number, y out number) is begin y:=x*x; exception when others then y:=0; end MySP1;

Write this code in VB6. Code 13-4 'call a stored function x = InputBox("Enter value to square") Set rs = cnn.Execute("select mysp(" & Val(x) & ") from dual", , adCmdText) MsgBox rs(0).Value 'call a stored procedure Dim cmd As ADODB.Command Set cmd = New ADODB.Command Dim x As Integer x = 9 Dim str As String str = "{? = CALL MYSP1(" & x & ",?)}" With cmd .Name = "MyProc" .CommandType = adCmdText .CommandText = str .Parameters.Append .CreateParameter("@Param1", adInteger, adParamInput) .Parameters.Append .CreateParameter("@Param2", adInteger, adParamOutput) .ActiveConnection = cnn End With rs.CursorLocation = adUseClient Dim a As Integer Call cnn.MyProc(x, a) MsgBox a

You can call stored procedures in similar way from VB.NET. It has already been shown in code 13-2.

Page 108: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 108 -

10 commandments of successful software development – You will start development with software requirements. You will honor thy users and communicate with them often. You will not allow unwarranted requirement changes. You will invest up front in software architecture. You will not confuse products with standards. You will recognize and retain your top talent. You will understand object-oriented technology. You will design web centric applications and reusable components. You will plan for change. You will implement and always adhere to a production acceptance process. Source: Ref. 17

Page 109: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 109 -

14. Program Architecture – Layered approach In earlier chapters we learned about 3-tier architecture programming. Now we learn more elegant Universal Layered Architecture (ULA) concept. In a 3-tier application, business routines are called in response to events in user interface. So, even here the front end and middle tier are somewhat entangled. The ULA tries to eliminate this problem. ULA organizes a database application in following layers conceptually. 1. User Layer 2. Business Layer 3. Data Layer 4. User Connection Layer 5. Database Layer 6. Data Connection Layers Here is a brief discussion of functionality of each layer. 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 It contains all business logic including calculations and validation. It processes request from user layer and places the results in data layer. It requests data from database through data connection 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. User Connection Layer

Page 110: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 110 -

It connects user layer and business layer to data layer. Database Layer It is the physical database. Data Connection Layer This layer communicates i.e. reads/writes from/to the database. It may be composed of DAO, RDO or ADO etc. 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! Take another example. Suppose you presently have an application with VB forms as front end. You can convert the user interface browser based by just changing user layer only. All other layers need not to be touched! 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.

Page 111: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 111 -

The Layered Architecture Development System (LADS) can be diagrammatically shown as in figure 21-1.

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.

USER LAYER – VB FORMS, HTML DOCUMENT ETC.

DATA LAYER – ADO RECORDSET ETC.

USER CONNECTION LAYER

DATA CONNECTION LAYER – ADO ETC.

DATABASE LAYER – ACCESS, ORACLE, SQL SERVER, SYBASE ETC.

BUSINESS LAYER (DLLs ETC.)

Page 112: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 112 -

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

Page 113: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 113 -

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

Page 114: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 114 -

in relevant fields in user interface. This is somewhat resembles showing elements of an array into some fields. We encapsulate all our business logic in business layer. Hey, I like to point out that business logic does not always mean commercial logic! It can be engineering or even artistic logic! This layer typically deals only with data layer and data connection layer. It processes data in data sets as per business requirement and then asks data connection layer to implement new data set values in the database. The actual coding of business layer is indeed a very complicated process. However, this is the big picture. Lastly, the user layer or what the user actually sees or interacts with the system. It can be VB forms, web browser or your own front-end tool. We only connect user interface with data layer. In ULA, user layer should not contain any business logic including data validation! Suppose, we have a VB form base front end now. If the client wants to access it through web, we just have to replace user layer with HTML forms - so easy! I think that's enough for your mental tonic. Now venture yourself in this wonderful concept. Good luck!

Page 115: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 115 -

Schematic diagram of various architectural implementations

2 – tier architecture Figure 14-2

3 – tier architecture (simplified form of ULA) (Shown here using ADO but can be implemented without it also)

Figure 14-3

Some Business Logic

Some Business Logic

Data read from ADO Recordset

ADO Recordset updated with modified data

Page 116: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 116 -

Universal Layered Architecture Figure 14-4

Communicates with database

ADO Recordset populates data layer and vice versa

Data is taken to user layer through User Connection for showing. After user makes any change to data, it is again carried to data layer, where business layer processes the data. Finally modified data is saved into database.

Processed data again refreshes data layer

Data is read from data layer into business layer and processed

Page 117: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 117 -

Can you still explain what exactly layers are? 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. Where do I use Object Oriented programming in layered application? 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. Does my database table design affect if I adopt object-oriented programming? No. Database table design is generally independent of what methodology (i.e. object oriented or procedural programming) you adopt in business layer.

Page 118: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 118 -

15. What language and Client/Server you should use? 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. 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.

My Name

Page 119: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 119 -

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. Since most commercial world applications are based on databases, designing and maintaining databases is an important task for programmers. SQL (Structured Query Language) is a language used to manipulate databases. It is not so versatile like a full-fledged programming language. The good news is that SQL can be connect with VB, C/++ or Java programs. 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. Choice of client server

Page 120: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 120 -

It is often a controversy what client server you should choose - Java/Oracle or VB/Oracle or VB/SQL Server and so on. This article aims to decide you which would be your best bet. This discussion applies to mainly OLTP applications. DSS applications usually have different requirements. Remember, the choice of platform mainly depends on your requirement - there's no hard and fast rule! For example, it's not a wise idea to use Oracle to help your kid's homework nor Access is good choice for capturing your 24x7 database, obviously. First step is to choose the database. You have following options,

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

Page 121: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 121 -

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). So, Access isn't so bad! Backup in Access is just simply copying the database files. For medium size applications (10+ users, hundreds of tables, complicated database code) you can hop for SQL Server. However, it runs only on Windows computers! Unix users are out of luck with SQL Server. SQL Server is good database. It is easier to handle (compared to Oracle), less trained people can administer it, uptime is good, and features are also good. The intuitive GUI of SQL Server makes a fun to use it. VB.NET applications have special type of integration with SQL Server. 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.

Page 122: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 122 -

Front End Database Comment VB Oracle Very common Forms Oracle Very common Java Oracle Very common VB SQL Server Very common Access Access Very common Access ODBC database Not uncommon Power Builder Sybase Common but less

prevalent nowadays Delphi Sybase Common but less

prevalent nowadays Java SQL Server Possible but never

heard of Other front end Other database Don't put fences beside

your imagination Forms Database other than

Oracle Possible but impractical

We shall examine each combination one after another. 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 is general purpose programming languages. It has matured itself for years and now with latest .NET version, it has become tremendous powerful. It now supports full object oriented methods including polymorphism, inheritance (even visually) and encapsulation. You can separate business logic in middle tiers by using VB DLLs (dynamic link library files). 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. Developer 2000 is an application consisting of mainly Forms and Reports. Forms act as front end of Oracle database. Note that Forms is not a general purpose programming language. It is a tool designed to act as an interface of Oracle database. Compared to VB, front-end development using Forms is much easier and faster when the database is Oracle. In forms, for basic database tasks

Page 123: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 123 -

(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. Sometimes, applications are deployed in 3 tier like Browser (user interface), Application server (middle tier) and database. Here business logics are encapsulated in middle tier. In this case, the application is middle tier centric. In fact, you can develop an application using Forms + Oracle and then deploy in 3 tier using Java (your Forms form will be converted to Java forms). Applications using Forms + Oracle are mostly database centric. 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. Also, it has become a fashion for many applications to make it database independent for higher customer base and marketability (though such applications are not good choice as the architecture of query processing and data storage varies widely between different databases). 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.

Page 124: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 124 -

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. In a nutshell, the choice is yours.

Page 125: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 125 -

16. Software Engineering 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. Contrary to popular belief, software engineering consists of many things other than just coding. In fact coding is only a small part in a typical software project. In this chapter, I shall discuss various aspects of software engineering in very concise manner to give you an overall idea of the subject. For detail discussion, please consult any standard software-engineering book. Background of Software Engineering In earlier times, programming was done in exploratory styles, i.e. every programmers used his/her own development techniques based on personal intuition, experience etc. However, as the size and complexity of the programs increased with time, structured programming technique was developed – which was based on control flow (eg. If – then – else and avoidance of GO TO statements etc.) concept. Though structured programming technique is still widely used nowadays for small and even medium sized applications, large programs are gradually being designed based on Object Oriented Analysis. Software Life Cycle A software life cycle is a series of identifiable stages that a software product undergoes during its lifetime. The typical stages are – feasibility study, requirement analysis and specification, design, coding, testing and maintenance. We shall now briefly discuss each of these steps. Feasibility study This is required to find out whether development of the product is technically and financially feasible. This is an overall analysis of the whole problem, possible strategies, cost factor etc. Requirement Analysis and Specification

Page 126: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 126 -

The aim of requirement analysis is to understand client/customer’s need thoroughly. Requirement analysis must be carried with due care. It has been found out that much confusion arises at a later stage about what to do exactly because of ambiguous requirement analysis. After the analysis is complete, the requirements are organized in a document known as Software Requirement Specification (SRS). The SRS clearly defines what the software is expected to do (eg. all functionalities, performance issues, input, output etc.) However it need not contain how to do it. The SRS document is normally considered as a contract between client and software development team. Design The goal of design is to transform the requirement specifications into a structure that is suitable of implementation some programming languages. The first step in this phase is Structured analysis i.e. preparation of detail analysis of different functions/objects to be used and identification of data flow among various functions/objects. For this purpose, Data Flow Diagrams (DFD) are drawn. After this, detail design is done. This step involves decomposing the system into various modules/objects and finding relations among them. Coding In this phase the design is implemented into codes. Each module is tested individually before integration. This is known as unit testing. Testing and Integration 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. Alpha testing – where the developers test the software. Beta testing – where some 3rd party test the product and reports the faults/errors etc. Acceptance testing – is normally done by the client before final delivery of the product. 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

Page 127: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 127 -

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. Consider the program of finding greatest common divisor of two numbers. Code 16-1 int FindGCD(int x, int y) …… Statement # { while(x != y) …… 1 { if(x > y) …… 2 x = x - y; …… 3 else y = y - x; …… 4 } …… 5 return x; …… 6 } A Control Flow Diagram (i.e. the sequence by which the statements of a program is executed) of the above code is shown below.

1

2

3 4

5

6

Figure 16-1 The logical paths of code 22-1 are: 1 – 2 – 3 – 5 – 1 – 5 – 6 for this test case x = 4, y = 3 1 – 2 – 4 – 5 – 1 – 5 – 6 for this test case x = 3, y = 4 1 – 5 – 6 for this test case x = 3, y = 3 Maintenance

Page 128: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 128 -

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. Software Development Methodology Models There are mainly 3 kinds of development methodologies, namely – waterfall model, prototype model and spiral model. Waterfall model – here all the above-discussed steps (i.e. feasibility study, requirement analysis and specification, design, coding, testing and maintenance) are followed sequentially. Prototype model – as the name suggests, a prototype or working version of the product is built first for better understanding of the functionality of the project. If the prototype is thrown away (after gathering information from it) then it is known as ‘Throw away prototype’. However, developers might consider converting the prototype into full working product by adding more and more functionality into it and by successive revisions. In this case, the method is called ‘Evolutionary prototype’. Spiral model – in this method the main steps followed are 1. Determination of objectives and alternatives 2. Evaluation of alternatives 3. Development of next level of the product 4. Evaluation of the product by the client These steps are followed iteratively until customer says that the product is ok. In real life projects, if the methodology to be adopted is completely known in advance (i.e. developers have made similar products in the past), normally waterfall model is followed. For new type of projects, prototype or spiral model is followed. However, in most projects, often a combination of these methods is performed.

Page 129: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 129 -

17. Exploring Extreme Programming concepts Extreme Programming (XP) is one of the most radical philosophies of programming. Though some of its concepts are reflected in other methodologies, some are quite new as well. Recently several software developers have become more productive following XP concepts. The 12 main XP practices are: 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.)

Page 130: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 130 -

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

Be courageous in pursuing values but avoid sacrificing yourself for them.

Page 131: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 131 -

18. Programming Tips 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. " Smart coding triangle => reuse, standardization, error coding. " Handle errors early – before they occur. " Code for errors as you go. " Avoid assumptions about user input. " Design all routines to be reused. " Never code for the same error twice. " Develop a systematic error coding methodology. The golden rules of error coding are: 1. Prevent all errors that can be anticipated and prevented. 2. Handle all errors that can be anticipated but not prevented. 3. Trap all errors that can't be anticipated.

" Always use Option Explicit. " Explicitly declare variables one per line. " Initialize all variables. " Always use ByVal or ByRef.

" Set explicit default values for optional arguments like:

sub ShowUsers(Optional ByVal UserCount As Variant = 0)

" Validate all arguments. " Don’t hardcode array bounds. " Always include an Else. " Avoid mixing data types in expressions. " Set objects to Nothing, for e.g. Set Form1 = Nothing " Set properties at runtime rather than on properties window. ERROR PREVENTION " Code defensively. " Filter and validate user input.

Page 132: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 132 -

" Use ‘Control Array’ wherever possible.

Debugging techniques Errors are every programmer’s birthright. A typical programmer’s day ends with red eyes, blue face and a pile of crumpled print outs and dozens of reference books all over the desk! Errors can be divided into 3 main categories – syntax error, runtime error and logical error. Regarding logical errors, I’ve nothing to say. It’s your task how you want to implement your logic. If you are using Integrated Development Environment like Visual Studio or Visual Café etc., syntax errors can be checked while you type as well as in compile time. 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.

Page 133: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 133 -

" 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! Learning a new language… what to look for? 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

A good comment in code neither insultsthe intelligence of another programmer,nor does it assume too much.

Page 134: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 134 -

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 In most languages, we have following data types – integer, long, double, single/float etc. Some languages have only ‘Number’ type for any number. ‘String’ data type is not found directly in C. Remember that, date and time are often handled differently in various languages! Take care how to convert from one type to another! 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. Derived data types Here come arrays, structures and ultimately classes! Some programming languages like Oracle PL/SQL treat arrays in a peculiar way! (There can be only two-column array or nested table.) In C/++ you can access array elements using pointers, but in most other languages you do the same in a simpler manner. 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

Page 135: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 135 -

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! Connecting with other programs 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!

Page 136: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 136 -

19. Programming in Spreadsheet 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. Consider the equation Z = 3x + 4y subjected to constraints 4x + 3y <= 80, 2x + 5y <= 180 and x => 0, y => 0. Our aim is find out the maximum value of ‘Z’ subjected to above constraints. To solve it by Excel, follow the steps illustrated. 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.

Page 137: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 137 -

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

Page 138: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 138 -

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

Remember to use proper ‘<=’ or ‘=>’ sign while specifying constraints. If everything seems ok, click the ‘Solve’ button. And that’s all. Excel will solve it within seconds and dumps you another dialog box like figure 19-6.

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.52 Y 353 Z 147.54 C1 805 C2 180

Figure 19-7

Page 139: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 139 -

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 Find the minimum value of P = a – 3b + 3c subjected to the constraints a, b, c >= 0, 3a – b + 2c <= 7, 2a + 4b >= - 12, - 4a + 3b + 8c <= 10. Answer is Pmin = - 28.6 for a = 6.2, b = 11.6 and c = 0. Remember spreadsheet is a very powerful as well as useful application. Try to exploit its full potential. Often you’ll find that spreadsheet is your best rescuer. Also note that since in all Microsoft products, Visual Basic is used as macro language, you can tap the full potential of Visual Basic form your Excel application! You can even add forms, command buttons, functions, procedures and every thing else in Excel! Spreadsheet is even good for small database applications as well.

Page 140: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 140 -

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. 1. Visual BASIC 5 Programming Guide to the Win32 API by Daniel Appleman

[It is an authoritative book on Windows API functions. It contains detail description of every API functions. It comes with a CD, which have the electronic version of the book.]

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.] 4. Fundamentals of Software Engineering by Rajib Mall, Prentice Hall of India,

ISBN 81-203-1445-X [Good for quick overall idea about software engineering] 5. Software Engineering - A Practitioner’s Approach by Pressman, McGraw

Hill, 5th Edition, ISBN 0-07-118458-9 [Contains details discussion of all aspects of software engineering]

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

8. Data Structures by Lipschutz, Schaum, ISBN 0-07-099130-8 [Nice book for an

introduction of data structures – array, linked list, stack, queue, tree, graph, searching, sorting etc. Easy language. Good explanation.]

9. Pointers in C by Kanetkar, BPB Publication, ISBN 81-7656-358-7 [All about

pointers. Lots of programming examples including data structures.] 10. C/C++ Annotated Archive by Friedman, Klander, Michaelis, Tata McGraw

Hill, ISBN 0-07-463607-3 [Contains some useful source codes. Discusses parsing of string and making your own compiler/interpreter in an understanding way. Includes step by step examples.]

Page 141: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 141 -

11. Oracle and Visual Basic Developer’s Handbook by Fedynich, Besaw, Tolinson, BPB Publication, ISBN 81-7656-270-X [Detail discussion of how do you make VB as a front end of an Oracle database.]

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

14. Programming ADO by David Sceppa, Microsoft Press, ISBN 81-7853-042-

2 [Discusses ADO in good details and quite informative. CD contains electronic version of the book.]

15. Professional Visual Basic 5 Business Objects by Rockford Lhotka, Wrox

Press, ISBN 1-861000-43-X [Discusses how to implement VB as front end in business applications. Presents every detail of implementation with many real life examples of 2-tier/3-tier architecture. It’s a big book but worth reading.]

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

17. Software Development - Building Reliable Systems by Marc Hamilton,

Prentice Hall ISBN 0-13-081246-3 [This book discusses various management concepts related with different stages of software development. Such as planning, recruiting people, trend in development, software life cycle, software development tools etc.]

18. Microsoft Developers Network (MSDN) journals and help files. 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.] 20. Journey of the Software Professional – a sociology of software development

by Luke Hohmann, Prentice Hall, ISBN 0-13-236613-4 [This book describes life of a software professional – how to adopt your design plan, how to tackle tough situation etc. It’s nice to read.]

Page 142: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 142 -

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

22. Access Database - Design & Programming by Steven Roman, O'Reilly

ISBN 81-7366-100-6 [This is a compact book which discusses database design basics, queries, database architecture in an easy understading and concise format. Also includes introduction to VBA, DAO and ADO - command references.]

23. Database System Concepts by Silberschatz, Korth & Sudarshan, McGraw

Hill ISBN 0-07-114810-8 [An authoratative book on database design. It includes in depth discussion on following topics - Entity, Relationship, SQL, Integrity constraints, RDBMS design, Object Oriented databases, Index, Query processing, Transactions, Recovery, Distributed database and many other advanced topics. Though this book involves mathematics/statistics to a great extent and quite a bit terse, you can consider yourself an expert in database system development if you thoroughly read (and understand) this book.]

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

Page 143: Better Understanding of Computer Programming

Better Understanding of Computer Programming

www.enselsoftware.com - 143 -

Better Understanding of Computer Programming

What you will find here – • All about returning values, objects, matrices,

structures from function/procedure • Applying all object oriented programming concept in

a single example in C++, VB/.NET and Java • How to write DLL in VB.NET and C++ • Introduction to Software Engineering • Database connectivity fundamentals • COM/CORBA/CLR – how do you use them • Pointers made easy • Concepts of language independent programming and

mixed language programming • How to become a more productive programmer • Programming in Spreadsheet • Universal Layered Architecture of database

application programming • How to choose best Client/Server combination • How to create VB.NET master detail forms • Updated for .NET

Bookstore section – Programming, Concept, VB, C/++, Database Published on the web by © Saikat Basak 2001-2004

USER LEVEL

Beginner Intermediate Advanced