Monday, March 30, 2009

New virus infects ATM , steals money from banks

Moscow: Automatic Teller Machines (ATM) may not be a safe way of transaction anymore as a new software virus has been found out which infects ATMs to steal money from bank accounts of their users. Doctor Web and 'Kaspersky Lab, two major anti-virus software producers have discovered such virus in the networks of several bank ATMs, which is able to collect information from bank cards.



This is a malicious program intended to infect and survive in ATMs. It is possible that new software will appear, aimed at illegitimately using banking information and removing funds," an official of the Kaspersky Lab was quoted as saying by RIA Novosti news agency.

According to the official, the virus is a Trojan which is able to infect the popular American Diebold brand of ATMs, used in Russia and Ukraine. Judging by the programming code used, there is a high probability that the programmer comes from one of the former Soviet republics.

The computer security experts say the number of infected ATMs is minimal but individual bank cardholders will not be able to detect whether an ATM is infected or not. However, banks can run security software to find out if their machines are at risk.

Courtesy: http://www.siliconindia.com

Chinese hackers infiltrate Indian embassy data

Toronto: China based hackers have infiltrated computers and stolen documents from hundreds of government and private offices around the world, including those of the Indian embassy in the U.S. and the Dalai Lama's organization, Canadian researchers said.



A vast electronic spying operation system, which infiltrated the computers, was being controlled from computers based exclusively in China, said the researchers in a report to be issued shortly. But they could not say conclusively that the Chinese government was involved. The group did also not identify the Indian embassies which were targeted.

The office of the Dalai Lama in India had asked the researchers based at the Munk Center for International Studies at the University of Toronto, to examine its computers for signs of malicious software, or malware.

Their examination unearthed a broader e-spying operation that, in less than two years, has infiltrated at least 1,295 computers in 103 countries, including many belonging to Indian embassies as well as the Dalai Lama's Tibetan exile centers in India, Brussels, London and New York.

The researchers believed that the e-spying operation, which they called GhostNet, had hacked into the computer systems at embassies of countries like Pakistan, Germany, Indonesia, Thailand and South Korea. The networks at foreign ministries of Bhutan, Bangladesh, Latvia, Indonesia, Iran and the Philippines, had been found similarly hacked.

Courtesy: http://www.siliconindia.com

Thursday, March 19, 2009

Handling Large Objects (LOB) - Oracle Database 10g

Handling Large Objects (LOB) - Oracle Database 10g

Large Objects (LOB)

Large Objects (LOBs) are a set of datatypes that are designed to hold large amounts of data. A LOB can hold up to a maximum size ranging from 8 terabytes to 128 terabytes depending on how your database is configured. Storing data in LOBs enables you to access and manipulate the data efficiently in your application.

BLOB - Binary Large Object
Stores any kind of data in binary format. Typically used for multimedia data such as images, audio, and video.

CLOB - Character Large Object
Stores string data in the database character set format. Used for large strings or documents that use the database character set exclusively. Characters in the database character set are in a non-varying width format.

NCLOB - National Character Set Large Object
Stores string data in National character set format. Used for large strings or documents in the National character set. Supports characters of varying width format.

BFILE - External Binary File
A binary file stored outside of the database in the host operating system file system, but accessible from database tables. BFILEs can be accessed from your application on a read-only basis. Use BFILEs to store static data, such as image data, that does not need to be manipulated in applications. Any kind of data, that is, any operating system file, can be stored in a BFILE. For example, you can store character data in a BFILE and then load the BFILE data into a CLOB specifying the character set upon loading.

Following are the examples, which I tried my self with oracle database 10g on Linux installation and pasted the contents. I have also put the neccessary comments for your understanding. Kinly let me know in case you have any doubts.

Storing a image file in oracle database table using DBMS_LOB package

Step 1) create a table

SQL> create table loadalbum
2 (name varchar2(100),
3 image blob);

Table created.

Step 2) Create a Directory object in database which will point to operating system directory.

SQL> CREATE OR REPLACE DIRECTORY DOCUMENTS AS '/dy/oracle/product/db10g/photo';

Directory created.

Step 3) Use the following procedure to insert a BLOB (image file) into database.
Note: The file (Sunset.jpg), which we are inserting into table should be present in DOCUMENTS directory location (/dy/oracle/product/db10g/photo) created above.

declare
l_blob blob;
l_bfile bfile;
begin
insert into loadalbum values ( 'Sunset', EMPTY_BLOB() )
// First create a Emply binary large object
returning image into l_blob; // and get a reference
l_bfile := bfilename( 'DOCUMENTS', 'Sunset.jpg' ); // Get the pointer to a file in directory
dbms_lob.fileopen( l_bfile ); // Open file
dbms_lob.loadfromfile( l_blob, l_bfile, dbms_lob.getlength( l_bfile ) );

dbms_lob.fileclose( l_bfile );
end;

SQL> select count(*) from loadalbum;

COUNT(*)
———-
1

Doing bulk upload of images to database.

You can use SQL*Loader utility to bulk upload regular text data. Same utility can be used to bulk upload images as well. Follow below steps to bulk up load the images

Step 1) Create a table

CREATE TABLE photoalbum (photolob BLOB);

Step 2) Create a file (example photos.txt ) which will contain list of images to be uploaded.

bash-2.05$ cat photos.txt
Winter.jpg
Water_lilies.jpg
Sunset.jpg
Blue_hills.jpg

Step 3) create a control file required by SQL*Loader to upload data. Create new file called loadphotos.ctl and insert following content into it.
load data
infile photos.txt
into table photoalbum
(ext_fname filler char(200),
photolob lobfile(ext_fname) terminated by EOF)

The meaning of above code is
"please load the data listed in the file photos.txt into a table called photoalbum. The data will be loaded into the column of that table called 'photoblob' and has lobfile characteristics… that is, it's binary data. Expect the file names for the binary files being loaded to be up to 200 characters in length. When you reach the end of the list of photos, terminate the load process".

Step 4) Run SQL*Loader

Please note that photos.txt is used in control file and we are not giving absolute path, but relative path. So control file and photos.txt should be in same directory. And so also all images. See below.

bash-2.05$ pwd
/dy/oracle/product/db10g/photo
bash-2.05$ ls -lrt
total 576
-rw-r–r– 1 db10g oinstall 105542 Jun 2 23:43 Winter.jpg
-rw-r–r– 1 db10g oinstall 83794 Jun 2 23:43 Water_lilies.jpg
-rw-r–r– 1 db10g oinstall 71189 Jun 2 23:43 Sunset.jpg
-rw-r–r– 1 db10g oinstall 28521 Jun 2 23:43 Blue_hills.jpg
-rw-r–r– 1 db10g oinstall 127 Jun 2 23:46 loadphotos.ctl
-rw-r–r– 1 db10g oinstall 54 Jun 2 23:48 photos.txt

bash-2.05$ sqlldr system/manager control=loadphotos.ctl

SQL*Loader: Release 10.2.0.1.0 - Production on Sat Jun 2 23:48:21 2007Copyright (c) 1982, 2005, Oracle. All rights reserved.Commit point reached - logical record count 4The above message shows that data is uploaded correctly. You can check the log file generated by SQL Loader at same location.SQL> select count(*) from photoalbum
2 ;

COUNT(*)
———-
4

Uploading Word Document to oracle database

You can use database tables for storing work documents as well. Please follow the below steps for doing the same

Step 1) Create table

CREATE TABLE my_docs
(doc_id NUMBER,
bfile_loc BFILE,
doc_title VARCHAR2(255),
doc_blob BLOB DEFAULT EMPTY_BLOB() );
// Default value will be empty binary large object

Step 2) Create directory object

SQL> CREATE OR REPLACE DIRECTORY DOC_DIR AS '/dy/oracle/product/db10g/doc';

Directory created.

Step 3) Create a procedure for uploading the file. Here inputs will be file_name and file_id.

Create or replace PROCEDURE load (in_doc IN VARCHAR2, in_id IN NUMBER) IS

temp_blob BLOB := empty_blob();

bfile_loc BFILE;
BEGIN
bfile_loc := BFILENAME('DOC_DIR', in_doc);

INSERT INTO my_docs (doc_id, bfile_loc, doc_title) VALUES (in_id, bfile_loc, in_doc);
SELECT doc_blob INTO temp_blob FROM my_docs WHERE doc_id = in_id FOR UPDATE;
DBMS_LOB.OPEN(bfile_loc, DBMS_LOB.LOB_READONLY);
DBMS_LOB.OPEN(temp_blob, DBMS_LOB.LOB_READWRITE);
DBMS_LOB.LOADFROMFILE(temp_blob, bfile_loc, dbms_lob.getlength(bfile_loc));

DBMS_LOB.CLOSE(temp_blob);

DBMS_LOB.CLOSE(bfile_loc);

COMMIT;
END load;

Step 4) Suppose I want to uplaod a .doc file present in the DOC_DIR directory (/dy/oracle/product/db10g/doc at OS level) created above.
The doc name is advait.doc.

Execute the above procedure as given below.

SQL> exec load('advait.doc', 1);

PL/SQL procedure successfully completed.

SQL> select count(*) from my_docs;

COUNT(*)
———-
1

The docs advait.doc will be saved in database table.

Updating LOB column of database table

Step 1) Create a table
CREATE TABLE book
(title VARCHAR2(40),
author VARCHAR2(40),
text CLOB,
author_pic BLOB);

Table created.

SQL>

Step 2) Insert some data

SQL> INSERT INTO book VALUES
2 ('My Book','Advait',EMPTY_CLOB(), EMPTY_BLOB());

1 row created.

Step 3) Update column using PL/SQL procedure

DECLARE
my_text_handle CLOB;
my_buffer VARCHAR2(4000);
my_add_amt NUMBER := 0;
my_offset INTEGER := 1;
BEGIN
my_buffer := 'This is my book';
my_add_amt := length(my_buffer);
SELECT text
INTO my_text_handle
FROM book
WHERE title = 'My Book' FOR UPDATE;

DBMS_LOB.WRITE(my_text_handle, my_add_amt, my_offset, my_buffer);
COMMIT;
END;

PL/SQL procedure successfully completed.

SQL>

SQL> select text from book;

TEXT
——————————————————————————–
This is my book

This can hold 4G of characters.


Courtesy: Internet Weblink

Monday, March 09, 2009

TCS likely to lay off 1,300 staffers



Chennai: India's IT major Tata Consultancy Services (TCS) will lay off around 1,300 employees - less than a percent of its global workforce- over the next few months, as these employees failed to meet performance standards, a company spokesperson said. The company has a total headcount of around 1.3 lakh.



Lay-offs have started at the company's development centers in Chennai, where over 200 employees have been asked to leave in the last fortnight, said TCS employees on condition of anonymity, as reported by The Economic Times.

A member of the TCS corporate communication team confirmed the development to the daily but did not put a number or place to it. "This is mostly employees who have been given a second chance to improve and haven't. They will be sent over a period, in the next few months. This will constitute less than a percent of our global workforce. We had to let go of 500 people last year on performance issues," the corporate communication team member said.

This comes less than a week after the company's CEO S Ramadorai said the company would review the variable pay component for its employees and also increase the working hours.

Asked about job cuts, he had said the company wasn't planning to cut jobs immediately but might have to if the situation worsened.

Employee expenses make up at least 53-54 percent of the company's total cost. Going by its analyst presentation for the third quarter ended December 2008, TCS had a total employee count of 1,30,343.

Wednesday, March 04, 2009

Oracle and Visual Basic using ADO - Sources: http://www.vb6.us/tutorials/oracle-and-visual-basic-using-ado

VB6 tutorial explains how you can access an Oracle database from within Visual Basic. It is a bit short as it was thrown together from a post on the vbforums.com page. However if you check out the Sample VB6 and Oracle Source Code that goes along with it. You should be able to easily understand what is going on. Read on and enjoy as you develop your Visual Basic Oracle application.

Oracle databases have been around for years, and although they are not as popular as their Microsoft counterpart, many business rely on Oracle backends for all their needs. Because of this, we must know how to interface with an Oracle database from within our VB6 application. This VB6 tutorial will walk us through exactly how to do this.

To access an Oracle database it is very similar to how you access any other database. We can simply use an ADO Connection object. We set the provider to be our Oracle provider and setup our connection string and password.

  1. Set dbConn = New ADODB.Connection
  2. With dbConn
  3. .Provider = "OraOLEDB.Oracle"
  4. .Properties("Data Source") = "DatabaseName"
  5. .Properties("User Id") = "someuser"
  6. .Properties("Password") = "somepassword"
  7. .Open
  8. End With

After we setup the connection all we do next is setup an ADO Command object that will be used with our oracle database. This is the same things we do for any Visual Basic database application.

  1. Set Cmd = New ADODB.Command
  2. Set Cmd.ActiveConnection = dbConn
  3. With Cmd
  4. .Parameters.Append .CreateParameter(, adVarChar, adParamOutput, 50)
  5. .Parameters.Append .CreateParameter(, adNumeric, adParamOutput)
  6. End With

Now is where things start being specific to our Oracle database. Getting a result set back from an Oracle SP is not as simple as it is in SQL Server. The results must come back to the calling program in something called a reference cursor (ref cursor). This will discuss what a ref cursor is and how to implement them and get data back.

Oracle creates an implicit cursor for every select query (I think that is the same for any database system). The cursor is simple the recordset results. If you are not going to use that result set for anything else (ie: to generate another query to execute) then you do not need to declare a cursor. But to get the result set out of Oracle you need something that is called a ref cursor. This ref cursor is more or less the same as and ADO recordset. You declare the ref cursor in code some where on the Oracle database, that ref cursor (sort of a structure in .Net) is then listed as an In and Out parameter of the SP.

You generate the select statement you want to run then open the ref cursor you created as follows:

  1. Open cRefCur For
  2. Select ....... (columns form whatever tables)
  3. From (table names)
  4. Where (conditions and Joins).
Standard SQL here with one big exception since if using Oracle 8i or earlier, Oracle at that release level did not support the Inner and Outer Join statements. You must use the Oracle version of them. Inners are just and equal sign as in Sales.ProductID = Prodcuts.ProductID. The Outer join is a lot messier, outer joins use the same equals sign and also a plus (+) sign on the deficient side of the equal sign.

This is the way to create the cursor:

First we create a package that will hold all the different return types:
  1. CREATE OR REPLACE PACKAGE cv_types AS

  2. TYPE WellData IS RECORD(
  3. WellName Varchar2(50),
  4. ResultsCount Number
  5. );
  6. TYPE CV_WEllData IS REF CURSOR RETURN WellData;

  7. End;
  8. /
Next we create a stored procedure that will use that ref cursor declared above:
(This procedure does not have any inputs, only output paramters).
  1. Create Or Replace Procedure WellCounting (
  2. pWellName OUT VARCHAR2,
  3. pCount OUT NUMBER,
  4. rsWellData IN OUT cv_types.CV_WEllData)

  5. AS

  6. BEGIN
  7. Open rsWellData For
  8. Select
  9. Wells.WELLNAME,Count(RESULTS.WELLID)
  10. Into
  11. pWellName,
  12. pCount
  13. From
  14. Wells, Results
  15. Where
  16. Wells.WellID = Results.WellID
  17. group by
  18. WEllName;

  19. EXCEPTION
  20. WHEN OTHERS THEN
  21. ROLLBACK WORK;
  22. RAISE;

  23. End WellCounting;
  24. /
We can then call the stored procedure from VB as shown in the included VB Projects.

An example of a stored procedure with input parameters is here:
  1. Create Or Replace Procedure OneWellCount (
  2. pWellID IN Number,
  3. pWellName OUT VARCHAR2,
  4. pCount OUT NUMBER,
  5. rsWellData IN OUT cv_types.CV_WEllData
  6. )

  7. AS
  8. BEGIN
  9. Open rsWellData For
  10. Select
  11. Wells.WELLNAME,Count(RESULTS.WELLID)
  12. Into
  13. pWellName,
  14. pCount
  15. From
  16. Wells, Results
  17. Where
  18. Wells.WellID = pWellID And
  19. Wells.WellID = Results.WellID
  20. group by
  21. WEllName;
  22. EXCEPTION
  23. WHEN OTHERS THEN
  24. ROLLBACK WORK;
  25. RAISE;

  26. End OneWellCount;
  27. /
We can also test these procedures (and ref cursors) from the SQL*Plus prompt by doing the following:
  1. Enter the command SET SERVEROUTPUT ON;
  2. Now we set up variables to hold data going into and out of the SP:
    Assuming we are using the first SP displayed, the we will need 3 variables:
    VARIABLE P1 VARCHAR2(50) This is because the field we are returning is 50 chars
    VARIABLE P2 Number This is a number coming back from the SP;
    VARIABLE P3 REFCURSOR This will hold the result set that is coming back
  3. From the SQL prompt enter:
    EXECUTE WellCounting( :P1, :P2, :P3);
  4. If the procedures completes successfully we can now display the output.
    The variable P1 and P2 will hold the last Well Name and number of results
    for that well name. The variable P3 will hold the complete recordset that
    is being returned. To display that result in SQL*Plus enter:
    Print P3

Naming Conventions in VB6.0


Introduction

I'm going to give you a little warning right from the start. The use of naming conventions is a religious issue for many programmers - sometimes ranking as high as the age-old goto debate or the choice of language. Some like naming conventions and some hate them. Most large programming organizations, however, do use them. I also think that many of those that passionately hate having naming conventions imposed on their work would probably (perhaps grudgingly) admit their usefulness.

Like many other "standards", what's more important than any particular naming convention, is that you choose a naming convention and use it faithfully. While you can probably get away with using your kids names for variable names in a 100 line program, you're inviting chaos if you take that approach with any serious application.

I will state one thing as a rule up front. Use Option Explicit. If you're new to Visual Basic and not familiar with it - its a feature that requires you to declare each variable in your program. Without Option Explicit, every time you type a new variable name, VB will create a new variable for you. As you can imagine, this can create bugs that are extrememly difficult to find if you happen to mistype a variable name somewhere. Other than pure laziness, there's simply no excuse for not using Option Explicit, so I have absolutely no sympathy for you if you ever have a bug caused by letting the compiler create a variable you didn't intend to create.

In the rest of this page, I'll describe the standards I've used for naming procedures, variables, and other objects of various types. Feel free to use my convention or invent your own.

Choosing Identifier Names

Most of the papers and books I've read that cover naming conventions spend a lot of time covering things like prefixes for different data types, etc., and neglect to cover the most basic concept - creating a good name for an identifier. Sure, it can help to use variable data type prefixes, but it doesn't help much if the name of your loop counter is intBunny and the procedure that contains the loop is called strDoSomething.

If you've done a decent job designing the application and the code, it doesn't take much effort to come up with decent names for the identifiers. The only problem that you're likely to run into is that the names may become excessively long. While very long names can be tiresome to use, its my opinion that you're better off to take the time to type an extra character or two than to use a meaningless or hard to interpret name.

Let's take a look at an example of how using appropriate variable names can help you write better code. Have you ever seen something like this:

For i = 0 To 10
For j = 1 To 100
List1.AddItem x(j, i)
Next
Next
Its more likely than not that in this case the array indexes have been reversed inside the inner loop. The programmer probably meant to do this:
    List1.AddItem x(i, j)
Its easy to eliminate this problem before its created by giving the loop indexes more meaningful names:
For iDivisionIdx = 1 To iDivisionCount
For iDistrictIdx = 1 To iDistrictCount
lstCustomers.AddItem sCustNames(iDivisionIdx, iDistrictIdx)
Next ' iDistrictIdx
Next ' iDivisionIdx
There's no confusion now over what loop index we're dealing with. Not only has the problem of transposing the indexes been elimiated - the entire loop construct is easier to read and understand because the names reflect the data being used.

Here are a few things to consider when naming identifiers in general:

  • Use a name that represents the data or the function.
    The name chosen should represent the data being used. If you are creating a variable that represents the total number of employees, EmployeeTotal or EmployeeCount would be good names.
  • Use abbreviations consistently.
    While its not necessary to have variable names that are 30 characters long, don't go overboard in abbreviating names. "Tm", for example, is only two characters shorter than "Time" and much less readable. There some common tags that are often used, such as Num for Number, Idx for Index, and so on. Feel free to use these if you wish, but if you do, use them consistently. Don't use Num some of the time and Number or Count at other times.
  • Make the name readable.
    A good rule to apply here is that you should be able to read your code to someone over the phone and have them be able to write it down without asking you for spellings.
  • Use a noun for variables.
    Pick a word that represents the data. This will make the code somewhat self-documenting and considerably easier to read.
  • Use a noun and a verb for procedures.
    If a procedure performs an action on an object, use a verb describing the action and a noun describing the object. For example, if a procedure adds a new contact to a database, "AddContact" might be an appropriate name.
  • Use caution with temporary variables.
    This is an area that can often cause problems such as the loop index error shown earlier. You may often need a temporary variable, such as a loop index or dummy variable to hold a return value from a function that you don't need. However, consider this: There's really no difference between a temporary variable and any other type of variable. They are all temporary since they only exist in the memory of the computer while the program is running and are always an abstraction created for the benefit of the programmer. The computer doesn't care what name you use, so why not take the time to type an extra character or two and use a meaningful name.

Naming Procedures

In a large, complex program, you may have hundreds or thousands of procedures. Using a naming convention and good identifiers can make your job of finding and using the procedures considerably easier.

One standard that is commonly used for procedure names is to use a verb describing the action performed followed by a noun describing the object acted upon. I have to say that I'm not particularly fond of this convention, mainly because it makes it difficult to find a procedure in an alphabetical listing. If you are using "Get" as a prefix to functions which return values (such as GetWindowText), you'll end up with a long list of GetThis and GetThat procedures. I've always thought that it makes more sense to use the same technique but to reverse the noun and the verb. GetWindowText would become WindowTextGet. This groups all the procedures associated with a particular object together. Unfortunately (for me anyway), I'm probably the only person to have attempted to use such a convention - so make your own choice to be consistent with the rest of the world or make up your own standard. Perhaps something else entirely works best for you.

Regardless of the naming convention you choose, there are a few things which a procedure name should do for you:

  • Use a name that represents an object and an action.
    Whether you use verb-noun or something else, the name of the procedure should indicate what the procedure does and what it does it to or with.
  • Be consistent in the order of the words.
    If you're going to use verb-noun, always use verb-noun. If you mix and match the two, you're only making your own life harder. While you may be able to remember all of the procedure names in a program with 100 procedures, you are unlikely to accomplish the same feat in a program with 1,000 or 10,000 procedures.
  • Be consistent in the verbs and nouns used.
    Just as you should be consistent when naming variables, you should also be consistent when naming procedures. If you're going to use SetFirstName, also use SetLastName rather than AssignLastName.
There's one other thing I'll mention which crosses the line between a coding standard and a naming convention. A well written procedure should do one task. If it does this, it will be easy to create a name for it. On the other hand, if the procedure does six things to four different objects, you may end up with a name like "AddCustomerAndUpdateRepPhoneAndFaxNumber". If you end up with a procedure name that looks like a run-on sentence, you probably haven't written a good procedure. If you need a name like "DoABunchOfStuff", you've almost certainly written a poor procedure. Before fudging a half-baked name, take another look at the code.

Naming Variables

Clearly its important with variables, just as with procedures and all identifiers, to use a name that is readable and representative of the data in use. There is, however, a debate among programmers over the use of various means of identifying variables by data type and usage. Some programmers like to use prefixes to identify the data type of the variable, while others prefer to use type declaration characters, and still others use neither and omit data type identification from the name entirely. The closest thing you'll find to a "sanctioned" naming convention for variables can be found in the MSDN/Visual Basic Starter Kit on the VB4 Professional edition CD under Visual Basic Programming Conventions from Microsoft Consulting Services.

I happen to like using data type prefixes, although I don't follow the Microsoft standards in all cases. Here's why:

  • The code is easier to read.
    I find that type declaration characters distracting when reading a code listing and difficult to verbalize.
  • You aren't bound to VB's data types.
    If you wish to define "hWnd" as a prefix for window handles, you can do so without breaking the standard.
  • You can design your own standard.
    The convention published by Microsoft specifies using "int" as a prefix for integers. I happen to prefer using just "i" - it saves a fair amount of typing for one of the most frequently used data types without sacrificing readability.
  • Some of the data types introduced in VB4 have no type declaration character.
    While I don't expect VB to drop the type declaration characters entirely in future versions, I also don't expect type declaration characters to be supported for any future data types. Also, many of the variables you work with are object variables which also have no type declaration character.
There are two other notable sets of tags I use for variable names.

The first is a prefix indicating the scope of the variable. I use "m" for module level variables and "g" for global variables. These tags not only identify the scope of the variable but also avoid name collisions and name shadowing between variables at different scopes.

The second is a prefix for parameters. I use this to avoid naming collisions between parameters and local variables and to distinguish between input and output variables. Input parameters are prefixed with "p" and output with "rp".

By using these additional modifiers, I can normally be sure that I never two variables in scope with the same name.

Modifier Tables

Here are most of the modifiers I use, grouped as follows:
  • Data Type Modifiers
  • Scope Modifiers
  • Miscellaneous Modifiers
  • Control Tags
  • DAO Objects

Data Type Modifiers

The data type modifiers are prefixed to the variable name.
Data Type Modifier
Boolean f
Integer i
Long l
String s
Byte b
Single sng
Double dbl
Date/Time dt
Currency cur
Variant vnt

Scope Modifiers

The scope modifiers are used before all other prefixes.
Scope Modifier
Global g
Module m

Miscellaneous Modifiers

Modifier Item
v Variant
This is used with normal data type prefixes to indicate that a variant is being used but a specific data type is expected. For example, in a database application a foreign key might normally be a long (l) but may also be Null, thus the use of a variant. The resulting prefix would be vl.
p Procedure Parameter
This prefix is used to help avoid name collisions when working with local variables and procedure parameters which otherwise share the same name. This modifier is prefixed to the base data type modifier.
rp Return Parameter
Used to indicate output (return values) passed through the parameter list in a procedure. This modifier is prefixed to the base data type modifier.
t User Defined Type
This modifier is used to indicate that the variable is a user-defined data type. It precedes all but the scope modifier.
_a Array
This modifier is appended to the variable name and is used to indicate that the variable is an array.
F - frm Form
The single upper case F is used in form names as specified at design time. The frm tag is used for variables representing forms. For variables, this tag follows the scope modifier.

Control Modifiers

These tags are used in control names and in variables representing controls.
Tag Control Type
chk Check Box
cmd Command Button
cbo Combo Box
dat Data Control
dir Directory List Box
drv Drive List Box
fil File List Box
fra Frame
hsb Horizontal Scroll Bar
img Image
lbl Label
lst List Box
opt Option Button
pnl 3D Panel
pic Picture Box
txt Text Box
tmr Timer
vsb Vertical Scroll Bar
Windows 95 Controls
il Image List
lv List View
sb Status Bar
tb Toolbar
tv Tree View

Data Access Objects

These tags are used with DAO objects and precede all but the scope modifier.
Tag DAO Object
ct Container
db Database
fld Field
grp Group
idx Index
prop Property
qd QueryDef
rs Recordset
rel Relation
td TableDef
usr User
ws Workspace

Given the number of available objects, custom controls, etc., that are available for use in Visual Basic, it would be impossible to come up with a comprehensive list of tags for every type of object. For those not listed (or maybe for those that are as well) you'll need to come up with your own tags. What's more important than using any particular set of tags is to choose a convention for the names and use it consistently. You're sure to be kicking yourself if you go back and look at your code after six months and discover that half of your Byte variables and half of your Boolean variables are prefixed with "b".


Summary

That was a lot to take in, but don't let yourself be confused or intimidated by the number of different modifiers and rules I use in naming objects. Once you get used to using a convention like this it becomes second nature and really does make life easier by allowing you to recognize the nature of the object by merely reading the name.

I'll repeat this again - it doesn't really matter what particular naming convention you choose as long as you name objects consistently. There's enough to learn and do in writing an application without expending excess effort in deciphering poor object names. Using a naming convention will eventually become automatic and that ultimately saves effort because its one less thing to think about.

Note: I have also published a Database Object Naming Conventions page. You might find it helpfull.

Originally written by Joe Garrick


Error/Exception Handling in VB6.0

Introduction

The various functions, statements, properties and methods available in Visual Basic and the components used in Visual Basic expect to deal with certain types of data and behavior in your applications. For example, the CDate() function can convert a value to a Date variable. The function is remarkably flexible in the type of information it can accept, but it expects to receive data that it can use to derive a date. If you provide input that it can't convert, it raises error number 13 - "Type mismatch" - essentially saying "I can't handle this input data."

In an application, this type of error may be a program logic error (you simply passed the wrong data) or it may be a data entry error on the part of the user (you asked for a date and the user typed a name). In the first case, you need to debug the program to fix the mistake. However, there is no way for you to anticipate the behavior of the end users of the application. If the user enters data you can't handle, you need to deal with the situation.

Dealing with errors at run-time is a two step process:

  1. Trap the Error
    Before you can deal with an error, you need to know about it. You use VB's On Error statement to setup an error trap.
  2. Handle the Error
    Code in your error handler may correct an error, ignore it, inform the user of the problem, or deal with it in some other way. You can examine the properties of the Err object to determine the nature of the error. Once the error has been dealt with, you use the Resume statement to return control to the regular flow of the code in the application.
In addition to dealing with run-time errors, you may at times want to generate them. This is often done in class modules built as components of ActiveX server DLLs or EXEs. It is considered good programming practice to separate the user interface from the program logic as much as possible, so if a server component cannot deal with an error, it should raise the error in its client application rather than simply display an error message for the user.
In VB5, there is an option that allows you to specify that an application has been designed for unattended execution (this is typically used for remote server applications). If you plan to allow the application to run unattended or on a remote computer, you can't simply display an error message because there will be nobody there to see it or dismiss the message box.

Trapping Errors at Run-Time

Before you can do anything to deal with a run-time error, you need to capture the error. You use the On Error statement to enable an error trap. On Error will redirect the execution in the event of a run-time error. There are several forms of the On Error statement:
  • On Error Goto label
    This form of the On Error statement redirects program execution to the line label specified. When you use this form of On Error, a block of error handling code is constructed following the label.
  • On Error Resume Next
    This form of the On Error statement tells VB to continue with the line of code following the line where the error occurred. With this type of error trap, you would normally test for an error at selected points in the program code where you anticipate that an error may occur.
  • On Error Goto 0
    On Error Goto 0 disables any error handler within the current procedure. A run-time error that occurs when no error handler is enabled or after an On Error Goto 0 is encountered will be handled using VB's default error handling logic.
It's not necessary to code an error handling routine in every procedure you write in Visual Basic. If an error is raised in a procedure, VB will work its way back up through the call tree looking for an error handler.
  1. Public Sub SubA()
  2. On Error Goto ProcError
  3. ' other code
  4. MsgBox FuncA()
  5. ProcExit:
  6. Exit Sub
  7. ProcError:
  8. MsgBox Err.Description
  9. Resume ProcExit
  10. End Sub
  11. Private Function FuncA() As Date
  12. FuncA = CDate("hi there")
  13. End Function
In this example, procedure SubA enables an error handler using the statement On Error Goto ProcError. When function FuncA is called in the MsgBox statement, the On Error Goto ProcError handler is still enabled. The CDate function in FuncA will generate error 13 (type mismatch) because CDate can't make a date from the input data. VB first looks in FuncA for an error handler. None was enabled, so the error is propogated back up the call tree to SubA. Since there is an error handler in SubA, program execution is redirected to the ProcError label in SubA. The MsgBox statement displays a description of the error and the Resume statement directs VB to continue execution at the ProcExit label.

There are some situations where VB cannot pass an error back up the call tree. This applies to Sub Main, most event procedures, and the Class_Terminate event procedure. Sub Main (if defined in the project property sheet) is the first code executed, so there is no procedure higher in the tree at application startup time. Most event procedures are also fired by Visual Basic when no other code is running so these are also at the top of the tree. Finally, the Class_Terminate event of class modules cannot raise an error because this event can also occur when no other code is executing in the application.

If an error is generated in one of these types of procedures and no error handler is enabled in the procedure, VB invokes its own default error handler, displays a message, and terminates the application. Because of this behavior, it is vital that you always code an error handler in Sub Main, all event procedures, and the Class_Terminate event for class modules.

Unlike the Class_Terminate event, the Class_Initialize event of a class module can raise an error or allow it to go untrapped. However, it is considered good programming practice to have classes trap their own errors, deal with them if possible, and if necessary raise errors explicitly, providing a number and description defined within the class.

You can code your classes to map any error the class encounters to class-defined error numbers, but given the large number of potential errors that could occur in an application, that may not always be practical. An alternative is to have the class assign specific numbers and descriptions to errors that are specific to problems with the code or data in the class (such as a value that violates a rule for the data) but pass out standard VB errors (such as error 13 - type mismatch) as is. This allows applications using the class to explicitly handle the errors exclusive to the class with customized code, but handle standard VB errors with more generic code.

Regardless of the approach you take, you must always ensure that private data within the class is valid and that code within the class cleans up any local or module level object variables it creates. This may require you to setup an error handler that traps errors, cleans up local object variables, and then raises the same error again.


Building Error Handlers

Trapping an error using the On Error statement is only the first step in dealing with run-time errors in your code. You must also deal with the error in some way, even if the error handling code is as simple as ignoring the error (a perfectly valid approach in some situations) or displaying a message for the user.

The first step in handling an error is determining the nature of the error. This is accomplished by examining the properties of Visual Basic's Err object. The Err object includes the following properties:

  • Number
    This is the error number that was raised.
  • Description
    This contains a descriptive message about the error. Depending on the error, the description may or may not be useful. (Microsoft Access, for example, has the the infamous error message "There is no message for this error.")
  • Source
    The Source property tells you what object generated the error.
  • HelpContext
    If a help file has been defined for the component that raised the error, this property will give you the help context ID. You can use this property along with the HelpFile property to display context sensitive help for errors in your application or as a debugging aid.
  • HelpFile
    This is the name of the help file that contains additional information about the error (if a help file has been provided).
It is important that you rely only on the error number to determine the nature of the error. While the Description and other properties may contain useful information, only the Number property is a reliable indicator of the exact error that occurred.

A common approach in coding an error handler is to build a Select Case block based on the Number property of the Err object:

  1. Public Sub SubA()
  2. On Error Goto ProcError
  3. ' code that raises an error
  4. ProcExit:
  5. Exit Sub
  6. ProcError:
  7. Select Case Err.Number
  8. Case X
  9. ' handle X
  10. Case Y
  11. ' handle Y
  12. Case Z
  13. ' handle Z
  14. Case Else
  15. ' default
  16. MsgBox Err.Description
  17. Resume ProcExit
  18. End Select
  19. End Sub
X, Y, and Z may be literal numbers (Case 13 ' type mismatch) or, if they are available, symbolic constants representing the numbers.
If you are building a class module that will raise class-defined errors, you should provide a public enumeration in the class that defines constants for any errors raised by the class. By providing constants, code that creates objects defined by the class can use the constants instead of the literal numbers and protect itself from changes in the actual numbers.
Once you have trapped and handled the error, you need to tell Visual Basic where to continue with program execution. There are several options available when an error handling block is entered using On Error Goto label:
  • Resume
    The Resume statement tells VB to continue execution with the line that generated the error.
  • Resume Next
    Resume Next instructs Visual Basic to continue execution with the line following the line that generated the error. This allows you to skip the offending code.
  • Resume label
    This allows you to redirect execution to any label within the current procedure. The label may be a location that contains special code to handle the error, an exit point that performs clean up operations, or any other point you choose.
  • Exit
    You can use Exit Sub, Exit Function, or Exit Property to break out of the current procedure and continue execution at whatever point you were at when the procedure was called.
  • End
    This is not recommended, but you can use the End statement to immediately terminate your application. Remember that if you use End, your application is forcibly terminated. No Unload, QueryUnload, or Terminate event procedures will be fired. This is the coding equivalent of a gunshot to the head for your application.
In addition to these statements, you can also call the Clear method of the Err object to clear the current error. This is most often used with inline error handling, as shown below:
  1. Public Sub CreateFile(sFilename As String)
  2. On Error Resume Next
  3. ' the next line will raise an error if the file
  4. ' doesn't exist, but we don't care because the
  5. ' point is to kill it if it does anyway.
  6. Kill sFilename
  7. Err.Clear
  8. ' code to create a file
  9. End Sub
This isn't a very robust example. There are many other things besides a file that doesn't exist that could cause the Kill statement to fail. The file may be read-only, there may be a network permissions error, or some other problem.

Handling Errors You Can't Handle

In most cases you can anticipate the most common errors and build code to deal with them. The error handling code might be as simple as a message to the user such as "This field requires a valid date." In some cases, however, you will encounter errors you didn't anticipate and you must find a way to deal with them.

There are two general approaches you can take to handling unanticipated errors:

  1. Assume that the error is not fatal to the application.
    Most errors will not be fatal to an application. The error may have been bad data provided by a user, a file that was not found, etc. Normally these kinds of errors can be corrected by the user and the application can continue. A default case in an error handler can simply display a message and exit the current procedure or continue.
  2. Assume that the error is fatal and the application must be terminated.
    In some cases, any error may be an application killer. This should be rare because this kind of error should be explicitly handled, if necessary by providing the user with the tools or information necessary to correct the situation. However, if a situation occurs where an unanticipated error is fatal, you must be sure to clean up after yourself before you shut down the application by unloading all forms and releasing any object variables you have created.
You should try to avoid the latter situation at all times. Displaying a message and shutting down or - worse yet - just pulling the application out from under the user will not be well received. If you must terminate an application due to some disastrous situation, be sure to provide as much information to the user as you can so that the situation can be resolved. An even better option is to code your error handlers to call code that corrects severe problems. For example, if you are designing a database application and encounter a corrupted database file, the error handling code could give the user the option of attempting to repair the damaged file. If a file cannot be found where it should be, write code to either look for it or give the user a file open dialog box so they can tell you where it went.

Raising Your Own Errors

There may be times when you need to generate errors in your code. This happens most often in class modules, but you can raise an error anywhere in a Visual Basic application. You raise an error by calling the Raise method of the Err object. Not surprisingly, the parameters of the Raise method are the same as the properties of the Err object: Number, Description, Source, HelpContext, and HelpFile. The values you provide for these parameters are available to error handling code that deals with the error you generate.

When you raise an error, you should make the information you provide via the Err object as informative as possible so that error handling code that deals with the error has the best possible opportunity to handle it.

  • Number
    You can raise any of the standard VB error numbers or provide your own number. If you are raising application-defined errors, you need to add the intrinsic constant vbObjectError to the number you raise so that your number does not conflict with built in error numbers.
  • Description
    Make the description as informative as possible. If invalid data is provided, it may be helpful to make that data part of the error message.
  • Source
    The Source provides the name of the object that generated the error. For example, if a Jet Database object raises an error, the Source property is "DAO.Database".
  • HelpContext
    If you provide a help file with the component or application, use the HelpContext parameter to provide a context ID. This can then be passed on to the MsgBox statement so that context sensitive help about the error is available.
  • HelpFile
    This is the name of the help file and is used in conjunction with the HelpContext parameter.
The following example is a hypothetical property procedure for a class module:
  1. ' in the declarations section
  2. Private mDate As Date
  3. Public Enum MyClassErrors
  4. errInvalidDate
  5. ' other errors
  6. End Enum
  7. ' a property procedure
  8. Public Property Let Date(vntDate As Variant)
  9. ' a variant is used to allow the property
  10. ' procedure to attempt to convert the value
  11. ' provided to a date
  12. If IsDate(vntDate) Then
  13. mDate = CDate(vntDate)
  14. Else
  15. ' invalid data
  16. Err.Raise _
  17. Number:=errInvalidDate, _
  18. Description:=CStr(vntDate) & " is not a valid date.", _
  19. Source:="Foo.MyClass"
  20. ' help context and file go here if a help file is available
  21. End If
  22. End Property
In this example, the property procedure tests for a valid date using the IsDate function. If the data provided is not a date, an error is raised using the constant from the error enumeration in the declarations section of the class module and a description that includes the bad data and the nature of the error.

Summary

Handling run-time errors is something all applications must do if they are to be robust and reliable.

The key points for error handling are:

  • There are two steps to handling run-time errors:
    1. Trap the error by enabling an error handler using the On Error statement.
    2. Handle the error by examining the properties of the Err object and writing code to deal with the problem.
  • Error handlers can be dedicated blocks of code enabled by using On Error Goto label or can be inline handlers enabled by using On Error Resume Next.
  • You can raise your own errors by calling the Raise method of the Err object.
  • Do your best to handle run-time errors rather than just inform the user of the problem, but if you can't do anything but display a message, make it as informative as possible.
  • Avoid terminating the application if at all possible.
The Err object was introduced in Visual Basic 4.0. For backward compatibility, VB continues to support the Err and Error statements and functions. Any new code should be using the Err object and legacy code should be converted to use the Err object.

By Joe Garrick

About OCX - Files

OCX - an Object Linking and Embedding (OLE) custom control.

An OCX is an Object Linking and Embedding (OLE) custom control, a special-purpose program that can be created for use by applications running on Microsoft's Windows systems. OCXs provide such functions as handling scroll bar movement and window resizing.

If you have a Windows system, you'll find a number of files in your Windows directory with the OCX file name suffix. Object Linking and Embedding was designed to support compound documents The Windows desktop is an example of a compound document and Microsoft used OLE to build it. OLE and the Component Object Model , a more general concept that succeeded OLE, support the development of "plug-and-play" programs that can be written in any language and used dynamically by any application in the system. These programs are known as components and the application in which they are run is known as a container. This component-based approach to application development reduces development time and improves the program capability and quality.

Windows application development programs such as PowerBuilder and Microsoft Access take advantage of OCXs. Microsoft now calls an OCX an ActiveX control, the component object under Microsoft's set of ActiveX technologies, of which the fundamental concept is the Component Object Model and, in a network, the Distributed Component Object Model (DCOM). An OCX or ActiveX control is actually implemented as a dynamic link library DLL module. (You can think of a DLL program as a "subprogram" that can be used by any number of application programs, each of which is a "container" for the DLL or OCX/ActiveX control "object.") Visual Basic and C++ are commonly used to write OCX or ActiveX controls.




Sources: http://www.topqualityfreeware.com/whatis/whatisaocx.html

Monday, March 02, 2009

Few Facts that we may not be aware off...

Something You May Not Know

 
    1. Coca-Cola was originally green.
 
    2.  The most common name in the world is  Mohammed.
 
    3.  The name of all the continents ends with the same letter that  they start  with.
 
    4.  The strongest muscle in the body is the  tongue.
 
    5.  There are two credit cards for every person in the United  States.
 
    6.  TYPEWRITER is the longest word that can be made using the  letters onlyon one row of the  keyboard.
 
    7.  Women blink nearly twice as much as  men!
 
    8.  You can't kill yourself by holding your  breath..
 
    9.  It is impossible to lick your  elbow.
 
    10.  People say "Bless you" when you sneeze because when you sneeze, your  heart stops for a  millisecond.
 
    11.  It is physically impossible for pigs to look up into the  sky.
 
    12.  The "sixth sick sheik's sixth sheep's sick" is said to be the toughest  tongue twister in the English  language.
 
    13.  If you sneeze too hard, you can fracture a rib. If you try  to
 
    Suppress a sneeze; you can rupture a blood vessel in your head or  neck and  die.
 
    14.  Each king in a deck of playing cards represents great king from history.  "Spades" - King David; "Clubs" - Alexander the Great;  " Hearts" - Charlemagne; "Diamonds" -  Julius  Caesar.
 
    15.  111,111,111 x 111,111,111 =  12,345,678,987,654,321
 
    16.  If a statue of a warrior on a horse has both front  legs in the air, the person died in battle. If the horse has one front  leg in the air, the person died as a result of wounds received in  battle. If the horse has a all four legs on the  ground, the person died of natural causes.
 
    17  What do bullet proof vests, fire escapes, windshield wipers and laser printers all have in  common?
    Ans. - All invented by  women.
 
    18.  Honey - This is the onlyfood that doesn't spoil.
 
    19.  A crocodile cannot stick its tongue  out.
 
    20.  A snail can sleep for three  years.
 
    21.  All polar bears are left  handed.
 
    22.  American Airlines saved $40,000 in 1987 by eliminating one olive from  each salad served in  first-class.
 
    23.  Butterflies taste with their  feet.
 
    24.  Elephants are the onlyanimals that can't  jump.
 
    25.  In the last 4000 years, no new animals have been  domesticated.
 
    26.  On average, people fear spiders more than they do  death.
 
    27.  Shakespeare invented the word 'assassination' and  'bump'.
 
    28.  Stewardesses is the longest word typed with onlythe left  hand.
 
    29.  The ant always falls over on its right side when  intoxicated.
 
    30.  The electric chair was invented by a  dentist.
 
    31.  The human heart creates enough pressure when it pumps out to  the body to squirt blood 30  feet.
 
    32.  Rats multiply so quickly that in 18 months, two rats could have over million  descendants.
 
    33.  Wearing headphones for just an hour will increase the bacteria in your ear  by 700  times.
 
    34.  The cigarette lighter was invented before the  match.
 
    35.  Most lipstick contains fish  scales.
 
    36.  Like fingerprints, everyone's tongue print is  different.