IT SOLUTIONS
Your full service technology partner! 
-Collapse +Expand
mprestwood
Mike Prestwood
-Collapse +Expand Profile
Member Info
Member Narration

POSTS:
MB Posts (1410)
KB Posts (1805)
KB Comments (76)
Blog (4 Topics)

KBPOSTSBYTYPE:
Tech Articles
FAQ Page (118)
Tips Page (70)
Definitions Page (96)
Code Snippets◄╣
Errors Library (15)
Resource Links (73)
File Library (49)

Search mprestwood:

Advanced

   ► KBProfile: mprestwood  Print This    Code Snippet DB  
Mike Prestwood

Mike Prestwood's Code Snippets Page

506 Code Snippets (short code examples).

These Code Snippets are organized by our community groups then by our knowledge base sub-topics.

Expand All

Group: C++


Topic: C++

-Collapse +Expand 1. C++/CLI Empty String Check (String.IsNullOrEmpty)
 

The .Net framework offers a static method in the string class: String.IsNullOrEmpty.

String^ s;
  
//s = ""; //Uncomment to test 2nd case.
  
if (String::IsNullOrEmpty(s))
{
  MessageBox::Show("empty string");
}



Topic: C++ Language Basics

-Collapse +Expand 2. C++ Assignment (=)
 

C++ uses = for it's assignment operator.

int Age;
string FullName; //#include <string>
  
Age = 42;
FullName = "Randy Spitz";
-Collapse +Expand 3. C++ Case Sensitivity (Yes)
 

C++ is case sensitive. In C and C++ commands and variable names are case sensitive.

The following first standard C++ snippet works:

printf("hello\n");
 
Printf("hello\n"); //>>>Does not work!
-Collapse +Expand 4. C++ Code Blocks ({ })
 

For C++, Java, JavaScript, and PHP, I prefer to put the first { at the end of the first line of the code block as in the example above because I see more C++ formatted that way.

int Dog::Bark() {
cout << "My first class method!" << endl;
return 0;
};
-Collapse +Expand 5. C++ Comments (// or /* ... */)
 

Commenting Code
C++ uses "//" for a single line comment and /* */ for a multiple line comment.

//Single line comment in MS (not ANSI compliant so do NOT use).
/* ANSI compliant single line comment. */
/*
Multiple line
comment.
*/
  
/*
* This is another popular
* way to write multi-line
* comments.
*/
-Collapse +Expand 6. C++ Comparison Operators (==, !=)
 

General Info: Round Floating Point Numbers

When comparing floating point numbers, make sure you round to an acceptable level of rounding for the type of application you are using.

Languages Focus: Comparison Operators

A comparison operator compares two values either literals as in "Hello" and 3 or variables as in X and Counter. Most languages use the same operators for comparing both numbers and strings. Perl, for example, uses separate sets of comparison operators for numbers and strings.

C++ Comparison Operators

Common comparison operators:

== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

//C++Builder example (ShowMessage is a VCL method).
//Does C++Builder evaluate the math correctly? No!
If (.1 + .1 + .1 == .3)
ShowMessage("correct");
else
ShowMessage("not correct");
-Collapse +Expand 7. C++ Constants (const)
 

In standard C++, you use const and static const to declare constants.

//C++Builder 2009 Example:
const String kName = "Mike";
const int kAge = 35;
  
ShowMessage("Hi " + kName + ", you are " + kAge + ".");
-Collapse +Expand 8. C++ Custom Routines
 

C++ is a hybrid language and as such offers global functions and class methods. A function must come before it's usage or you can prototype the function.

void sayHello(string pName) {
cout << "Hello " + pName + "\n";
};
 
int add(int p1, int p2) {
int result;
 
  result = p1 + p2;
return result;
};
-Collapse +Expand 9. C++ Deployment Overview
 

You can use any of the many free and commercially available installation packages.

In Visual Studio.Net, you can create a Setup and Deployment project by using any of the templates available on the New Project dialog (Other Project Types).

C++Builder 2007 and 2009 are bundled with InstallAware Express CodeGear Edition installer.

-Collapse +Expand 10. C++ Development Tools
 

Languages Focus: Development Tools

Primary development tool(s) used to develop and debug code.

C++ Development Tools

Many compilers and development tools are available. Common development tools include Microsoft Visual C++, CodeGear C++Builder, and Eclipse.

With Visual C++ you use Microsoft's C++ syntax variations based on standard C++ or Microsoft's new C++/CLI syntax standard.

With C++Builder, you code using standard C++ with early support for the upcoming C++0x standard and using the VCL/RTL libraries. The VCL/RTL libraries are in common with Delphi which is based on Object Pascal. Within a project, C++Builder can use both C++ units and Delphi units.

With most C++ tools, you can also use your favorite C and C++ libraries too.

-Collapse +Expand 11. C++ End of Statement (;)
 

C++ uses a semicolon ";" as an end of statement specifier and you can put multiple statements on a single line of code if you wish as well as split a single statement into two or more code lines.

printf("Hello1");
printf("Hello2");
  
printf("Hello3"); printf("Hello4");
  
printf
   ("Hello5");
-Collapse +Expand 12. C++ File Extensions (.CPP and .H)
 

Important standard C++ file extensions:

  • .CPP = C++ Source file. Your startup source file will have a main() routine.
  • .C = C source file (sometimes used for C++ source files too).
  • .H = Header include file.

Some important Visual C++ file extensions:

-Collapse +Expand 13. C++ If Statement (if..else if..else)
 

Same as standard C.

//C++Builder example using the VCL ShowMessage.
int x;
  
x = 8;
  
if (x == 10) {
ShowMessage("x is 10.");
} else if (x < 10) {
ShowMessage("x is less than 10.");
} else {
ShowMessage("x must be greater than 10.");
}
-Collapse +Expand 14. C++ Literals (quote)
 

Literals are quoted as in "Prestwood". If you need to embed a quote use a slash in front of the quote as in \"

printf("Hello\n");
printf("Hello \"Mike\".\n");
 
cout << "Hello" << endl;
cout << "Hello \"Mike\".\n";
-Collapse +Expand 15. C++ Logical Operators
 

C++ logical operators:

&& and, as in this and that
|| or, as in this or that
! Not, as in Not This
^ either or, as in this or that but not both

//Given expressions a, b, c, and d:
if !((a && b) && (c || d)) {
  //Do something.
}
-Collapse +Expand 16. C++ Overview and History
 

Language Overview: C++ is a hybrid traditional C and OOP language. You code either in a traditional approach using functions, procedures, and global data, or you code using an OOP approach, or a mixture of both.

Target Platforms: C++ is suitable for creating any type of native code applications for many different platforms. The focus of this information is on creating native code Win32 applications that run on Microsoft Windows.

-Collapse +Expand 17. C++ String Concatenation (+ or append)
 

The + operator can be used with any combination of C++ strings, C strings and characters.

string fullname;

fullname = "Mike ";
fullname.append("Prestwood");

cout << "Hello " + fullname + "." << endl;
-Collapse +Expand 18. C++ Unary Operators
 

An operation with only one operand (a single input) such as ++X and --Y.

-Collapse +Expand 19. C++ Variables (int x=0;)
 

Variable names are case sensitive. The fundamental variable types in C++ are char, short int, int, long int, bool, float, double, long double, and wchar_t. The integer data types char, short, long and int can be either signed or unsigned. Signed variables are positive and negative. Unsigned variables are positive only.

C++, Java, and C# all use C-like variable declaration.

int Age;
int Age = 43;
float a, b, c;
string FullName; //#include 
unsigned short int FamilyMemberCount;
-Collapse +Expand 20. C++/CLI Code Blocks ({ })
 

Same as standard C++. For C++, Java, JavaScript, and PHP, I prefer to put the first { at the end of the first line of the code block as in the example above because I see more C++ formatted that way.

int Dog::Bark() {
cout << "My first class method!" << endl;
return 0;
};
-Collapse +Expand 21. C++/CLI File Extensions (.CPP and .H)
 

The C++/CLI standard file extensions are the same as standard C++. Important C++ file extensions:

  • .CPP = C++ Source file. Your startup source file will have a main() routine.
  • .C = C source file (sometimes used for C++ source files too).
  • .H = Header include file.

Some important Visual C++ file extensions:




Topic: Standard C++

-Collapse +Expand 22. C++ Exception Trapping (try/catch)
 

Languages Focus: Exception Trapping

A common usage of exception handling is to obtain and use resources in a "try-it" block, deal with any exceptions in an "exceptions" block, and release the resources in some kind of "final" block which executes whether or not any exceptions are trapped.

C++ Exception Trapping

try {
  //Some code.
}
catch(AnError) {
  //Error code here.
}
-Collapse +Expand 23. C++ Report Tools Overview
 

Use any report writer you are comfortable with. C++Builder 2009 comes bundled with Rave Reports and Crystal Reports remains popular for Visual C++.




Topic: C++ Language Details

-Collapse +Expand 24. C++ Associative Array (map)
 

General Info: Associative Array

A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'

Languages Focus: Associative Array

Associative arrays are also known as a dictionary or a hash table in other languages.

C++ Associative Array

map<string, int> mymap;
mymap.insert(AValuePair);
-Collapse +Expand 25. C++ Inlining (inline)
 

Use the inline keyword to tell the compiler to inline a routine.

inline int add(int p1, int p2) {
int result;
 
  result = p1 + p2;
return result;
};
-Collapse +Expand 26. C++ Overloading
 

C++ Overloading

  • Operator - Yes for C++, no for C. Almost all operators can be overloaded for user-defined types
  • Method -
-Collapse +Expand 27. C++ Pointers
 

C++ uses both pointers and references. Use the * operator to declare a pointer and use the & operator to declare a reference.




Topic: C++/CLI Language Basics

-Collapse +Expand 28. C++/CLI Assignment (=)
 

C++/CLI uses = for it's assignment operator.

int Age;
string FullName;
  
Age = 42;
FullName = "Randy Spitz";
-Collapse +Expand 29. C++/CLI Case Sensitivity (Yes)
 

Same as standard C++. Both standard C++ and C++/CLI are case sensitive. In C and C++ commands and variable names are case sensitive.

The following first C++/CLI snippet works:

MessageBox::Show("Hello");
 
messagebox::SHOW("Hello"); //>>>Does not work!
-Collapse +Expand 30. C++/CLI Code Blocks ({ })
 

Same as standard C++. For C++, Java, JavaScript, and PHP, I prefer to put the first { at the end of the first line of the code block as in the example above because I see more C++ formatted that way.

class Cyborg {
public: System::Void IntroduceYourself() {
MessageBox::Show("Hi");
}
};
-Collapse +Expand 31. C++/CLI Comments (// or /* ... */)
 

Commenting Code
Same as standard C++. C++ uses "//" for a single line comment and /* */ for a multiple line comment.

//Single line comment in MS (not ANSI compliant so do NOT use).
/* ANSI compliant single line comment. */
/*
Multiple line
comment.
*/
  
/*
* This is another popular
* way to write multi-line
* comments.
*/
-Collapse +Expand 32. C++/CLI Comparison Operators (==, !=)
 

Same as standard C++.

//Does C++/CLI evaluate the math correctly? No!
if (0.1 + 0.1 + 0.1 == 0.3)
MessageBox::Show("correct");
else
MessageBox::Show("not correct");
-Collapse +Expand 33. C++/CLI Constants (const or literal)
 

C++/CLI supports the const and static const keywords of standard C++ as well as the new literal keyword. A literal is equivalent to static const in standard C++ and Microsoft's documentation recommends to replace static const with the new literal keyword because a leteral is available in metadata; a static const variable is not available in metadata to other compilers.

You can use static const within the class declaration or locally within a method. However, literal is only valid in the class declaration section and const is only valid within a method.

//some method {
const String^ MyName = "John";
static const Int32 MyAge = 27;
//}
// public class SomeClass : public Object {
public:
  literal double Pi = 3.14159;
  literal String^ MyName = "Mike";
  static const Int32 MyAge = 35;
//...
-Collapse +Expand 34. C++/CLI Deployment Overview
 

C++/CLI projects require the .Net framework and any additional dependencies you've added such as Crystal Reports.

In Visual Studio.Net, you can create a Setup and Deployment project by using any of the templates available on the New Project dialog (Other Project Types).

To create a ClickOnce deploy package, search the internet for mage.exe and mageui.exe.

In addition, you can use any of the many free and commercially available installation packages.

-Collapse +Expand 35. C++/CLI Development Tools
 

The only development tool I know that supports C++/CLI at this time is Visual Studio.Net. C++/CLI was introduced in VS.Net 2005 and continued in VS.Net 2008.

-Collapse +Expand 36. C++/CLI End of Statement (;)
 

Same as standard C++. C++ uses a semicolon ";" as an end of statement specifier and you can put multiple statements on a single line of code if you wish as well as split a single statement into two or more code lines.

//.Net WinForms example.
//Add, using namespace System::Windows::Forms;
MessageBox::Show("Hello1");
MessageBox::Show("Hello2");
MessageBox::Show("Hello3");
   
MessageBox::Show("Hello4"); MessageBox::Show("Hello5"); 
  
MessageBox:: 
  Show 
    ("Hello6");
-Collapse +Expand 37. C++/CLI File Extensions (.CPP and .H)
 

The C++/CLI standard file extensions are the same as standard C++. Important C++ file extensions:

  • .CPP = C++ Source file. Your startup source file will have a main() routine.
  • .C = C source file (sometimes used for C++ source files too).
  • .H = Header include file.

Some important Visual C++ file extensions:

-Collapse +Expand 38. C++/CLI If Statement (if..else if..else)
 

Same as standard C.

int x;
  
x = 8;
  
if (x == 10) {
MessageBox::Show("x is 10");
} else if (x < 10) {
MessageBox::Show("x is less than 10");
} else {
MessageBox::Show("x must be greater than 10");
}
-Collapse +Expand 39. C++/CLI Inlining (Automatic)
 

In C++/CLI, inlining is automatically done for you by the JIT compiler for all languages and in general leads to faster code for all programmers whether they are aware of inlining or not.

-Collapse +Expand 40. C++/CLI Literals (qoute)
 

Same as standard C++. Literals are quoted as in "Prestwood". If you need to embed a quote use a slash in front of the quote as in \"

MessageBox::Show("Hello");
MessageBox::Show("Hello \"Mike\".");
  
//Does ASP evaluate this simple
//floating point math correctly? No! 
if ((.1 + .1 + .1) == 0.3) {
MessageBox::Show("Correct");
} else {
MessageBox::Show("Not correct");
}
-Collapse +Expand 41. C++/CLI Logical Operators
 

Same as C++ and Java. C# logical operators:

& and, as in this and that No Short Circuit
&& and, as in this and that short circuits
| or, as in this or that No Short Circuit
|| or, as in this or that short circuits
! Not, as in Not This
^ either or, as in this or that but not both

//Given expressions a, b, c, and d:
if !((a && b) && (c || d)) {
  //Do something.
}
-Collapse +Expand 42. C++/CLI Overview and History
 

Language Overview: A.k.a. C++.Net. Microsoft's C++ language for .Net Framework development.

Language History: C++/CLI was introducted with VS.Net 2005 and replaced Managed C++ (introduced with VS.Net 2002). C++/CLI was standardized by ECMA-372.

Target Platforms: C++/CLI is suitable for creating .Net Framework applications.

-Collapse +Expand 43. C++/CLI String Concatenation (+)
 

C++/CLI performs implicit casting of numbers to strings. To concatenate two strings, a string to an integer, or a string to a floating point number, use the + operator. For example, to convert a floating point number to a string just concatenate an empty string to the number as in "" + 3.2.

//Implicit casting of numbers.
//
//This fails:
//MessageBox::Show(3.3);
//
//This works:
MessageBox::Show("" + 3.3);



Topic: C++ OOP

-Collapse +Expand 44. C++ Abstraction (=0 in a virtual method)
 

AbstractMemberFunction is a pure virtual function makes this class Abstract class indicated by the "=0"and NonAbstractMemberFunction1 is a virtual function.

class AbstractClass {
public:
virtual void AbstractMemberFunction() = 0;
  virtual void NonAbstractMemberFunction1();

};
-Collapse +Expand 45. C++ Class..Object (Yes)
 

Languages Focus: Class..Object

In short, a class is a data type, and an object is an instance of a class type. A class has methods (routines), properties (member variables), and a constructor. The current values of the properties is the current state of the object. The UML is one of the diagraming disciplines that allows you to document the various changing states of a series of objects.

C++ Class..Object

-Collapse +Expand 46. C++ Constructors (Use Class name)
 

A member function with the same name as the class.

class X {
public:
X(); // constructor for class X
};
-Collapse +Expand 47. C++ Destructor (~ClassName)
 

A member function with the same name as the class prefixed with a ~ (tilde). C++ destructors are automatically called when an object goes out of scope, or when you delete a dynamically allocated object. Every class can have only one destructor.

class Cyborg {
public:
// Constructor for class Cyborg
Cyborg();
  
// Destructor for class Cyborg
~Cyborg();
};
-Collapse +Expand 48. C++ Inheritance (: public ParentClass)
 

In C++ you use the class keyword to signify a class and a colon followed by the parent class name for inheritance.

In the following example, a terminator T-600 is-an android. 

class Android {
};
 
class T-600: Public Android {
};
-Collapse +Expand 49. C++ Inheritance-Multiple (Yes)
 

C++ supports both multiple implementation inheritance and multiple interface inheritance.

-Collapse +Expand 50. C++ Interfaces (No, but mimic it.)
 

You can mimic an interface by using a class that has only pure-virtual functions and no member variables.

-Collapse +Expand 51. C++ Member Visibility
 

C++ implements class and member visibility specifiers traditionally. Note the colon at the end of each visibility specifier and the semi-colon at the end of the class (the end of the statement).

class Cyborg: Public AParentClass {
public:
 
protected:
 
private:
};
-Collapse +Expand 52. C++ Prevent Derivation
 

Make the constructor a private member of the class.

-Collapse +Expand 53. C++ Static Members (static)
 

C++ supports static methods and static member fields using the static keyword.

class MyUtils {
public:
static void MyStaticMethod();
};



Topic: C++/CLI OOP

-Collapse +Expand 54. C++/CLI Base Class (System::Object)
 

In C++/CLI, the Object keyword is an alias for the base System::Object class and is the single base class all classes ultimately inherit from.

-Collapse +Expand 55. C++/CLI Base Class (System::Object)
 

In C++/CLI, the Object keyword is an alias for the base System::Object class and is the single base class all classes ultimately inherit from.

-Collapse +Expand 56. C++/CLI Finalizer (~ClassName)
 

Unlike standard C++, C++/CLI uses the .Net garbage collector to free managed object instances. Prism does not have nor need a true destructor.

In .Net, a finalizer is used to free non-managed objects such as a file or network resource. Because you don't know when the garbage collector will call your finalizer, Microsoft recommends you implement the IDisposable interface for non-managed resources and call it's Dispose() method at the appropriate time.




Topic: C++/CLI WinForms

-Collapse +Expand 57. C++/CLI Report Tools Overview
 

Use any report writer you are comfortable with but Crystal Reports remains popular for Visual C++ and C++/CLI.




Group: Pascal and Delphi Coding





Topic: Delphi for Win32

-Collapse +Expand 58. Delphi Array (x=Array[0..3] of string;)
 

Delphi supports both static and dynamic arrays.

var
  MyArray: array[0..3] of string;
  i: Integer;
begin
  MyArray[0] := 'Mike';
  MyArray[1] := 'Lisa';
  MyArray[2] := 'Felicia';
  MyArray[3] := 'Nathan';
  
  for i := 0 to High(MyArray) do
    ShowMessage(MyArray[i]);
end;
-Collapse +Expand 59. Delphi Empty String Check (length(s) = 0)
 

Length() or SizeOf() will correctly identify an unassigned string variable or an empty string.

if length(s) = 0 then
  ShowMessage('empty string');
-Collapse +Expand 60. Delphi Event Handler
 

Many objects in Delphi have events you can use to trigger code. For example, when you add a form to your project you have access to the form events such as onCreate, onShow, onHide, onDockDrop, etc. In addition, Delphi offers module level events initialization and finalization sections.

-Collapse +Expand 61. Delphi Exception Trapping (try..except, try..finally)
 

Delphi also offers a try...finally where code will execute in the finally section no matter what. It's common to put a try...except inside a try...finally:

var
y : Double;
begin
try
y := 0;
y := (1/y);
ShowMessage(FloatToStr(y));
except
ShowMessage('You cannot divide by zero.');
end;
end;
-Collapse +Expand 62. Delphi Inline Code (asm)
 

In Delphi, you can inline assembler code using the asm keyword.

-Collapse +Expand 63. Delphi Member Events
 

In Delphi, member events are essentially properties of the type method pointer.




Topic: Tool Basics

-Collapse +Expand 64. Delphi Deployment Overview
 

Delphi create native code Windows applications so you can create an EXE with no dependencies that will run on any Windows computer. If you add dependencies (reports, database libraries, DLLs, etc.) use a Windows installer to build an installation program.

D2007 and D2009 are bundled with InstallAware Express CodeGear Edition installer.




Topic: Language Basics

-Collapse +Expand 65. Delphi Assignment (:=)
 

Delphi uses := for it's assignment operator.

var
  FullName: String;
  Age: Integer;
begin
  FullName := "Randy Spitz";
Age := 38;
end
-Collapse +Expand 66. Delphi Case Sensitivity (No)
 

Object Pascal is generally not case sensitive.

Variables and commands are not case sensitive.

var
FullName: String;
begin
fullname := 'Mike Prestwood';
ShowMessage(fullNAME);
SHOWMESSAGE(FULLNAME);
showmessage(fullname);
end;
-Collapse +Expand 67. Delphi Code Blocks (begin..end)
 

Object Pascal requires the semi-colon after the "declaration" part.

function DoSomething : integer;
var
  a, b : integer
begin
  a := 1;
  b := 2;
  
  result := a + b;
end;
-Collapse +Expand 68. Delphi Comments (// or { ... } or (* ... *))
 

Delphi uses // for a single line comment and both {} and (**) for multiple line comments. Although you can nest different types of multiple line comments, it is recommended that you don't. A special comment. Delphi compiler directives are in the form of {$DIRECTIVE}. Of interest for comments is using the $IFDEF compiler directive to remark out code.

//This is a single line comment.
 
{
Multiple line
comment.
}
 
(*
This too is a
multiple line comment.
*)
 
{$IFDEF TEMPOUT}
//...code here
{$ENDIF}
-Collapse +Expand 69. Delphi Constants (Const kPI: Double=3.1459;)
 

In Delphi, you define constants similar to how you define variables but use the Const keyword instead of the Var keyword. Declare global constants in a unit's interface section and unit constants (scope limited to unit) in the implementation section. Declare local constants above the begin..end block.

Const 
  kFeetToMeter: Double = 3.2808;
  kMeterToFeet: Double = .3048;
  kName: String = "Mike";
 
//Local constants:
procedure SomeProcedure;
const
  kPI: Double=3.1459;
begin
end;
-Collapse +Expand 70. Delphi Development Tools
 

Languages Focus: Development Tools

Primary development tool(s) used to develop and debug code.

Delphi Development Tools

CodeGear Delphi is the primary tool of choice for most developers but other Object Pascal language development tools do exist and some are quite good.

-Collapse +Expand 71. Delphi End of Statement (;)
 

Languages Focus: End of Statement

In coding languages, common End of statement specifiers include a semicolon and return (others exist too). Also of concern when studying a language is can you put two statements on a single code line and can you break a single statement into two or more code lines.

Delphi End of Statement

Object Pascal uses a semicolon ";" as an end of statement specifier and you can put multiple statements on a single line of code and put a single statement on two or more code lines if you wish.

WriteLn('Hello1');
WriteLn('Hello2');
WriteLn('Hello3');

//Same line works too:
WriteLn('Hello4'); WriteLn('Hello5');

//Two or more lines works too:
WriteLn
('Hello6');
-Collapse +Expand 72. Delphi File Extensions
 

Common source code file extensions include:

  • .BDSPROJ - Project, Borland Developer Studio project file holds compiler options, etc. This is the file you open.
  • .DCU - Delphi Compiled Unit file.
  • .DFM - Delphi Win32 form file (a text resource file).
  • .DPR - Delphi project file. Primary project "source" file.
  • .PAS - Delphi unit source file.
-Collapse +Expand 73. Delphi If Statement (If..Else If..Else)
 

Notice in the more complete example that the semicolon for the begin..end block after end is not included. That tells the compiler something else is coming (the statement is not finished). Also note the semicolon is missing right before the final "else" statement.

Note: The following example uses floating point literals. In Delphi, to specify a fractional floating point literal between 1 and -1, you preceed the decimal with a 0; otherwise, you will get a compiler error (i.e. .1 + .1 does not work).

if (0.1 + 0.1 + 0.1) = 0.3 then
  ShowMessage('Correct')
else
  ShowMessage('Not correct');
 
//Complete example:
if x = true then
begin
  ShowMessage('x is true');
end
Else If y = 'Mike' Then 
  ShowMessage('hello mike')
Else 
  ShowMessage('last option');
-Collapse +Expand 74. Delphi Literals (apostrophe)
 

Literals are single quoted (the apostrophe) as in 'Prestwood'. If you need to embed an apostrophe use two apostrophies in a row.

ShowMessage('Hello');
ShowMessage('Hello Mike''s website.');
-Collapse +Expand 75. Delphi Logical Operators
 

Delphi logical operators:

and and, as in this and that
or or, as in this or that
not Not, as in Not This
xor either or, as in this or that but not both

//Given expressions a, b, c, and d:
if Not (a and b) and (c or d) then
  //Do something.
-Collapse +Expand 76. Delphi Overview and History
 

CodeGear Delphi Helmet IconLanguage Overview: Delphi programming language is a type-safe language consisting of hybrid traditional Pascal and OOP features. You code either in a traditional approach using functions, procedures, and global data, or you code using an OOP approach, or a mixture of both.

Target Platforms: Delphi for Win32 is most suitable for creating native code Win32 applications that run on Microsoft Windows.

-Collapse +Expand 77. Delphi Parameters (var, const)
 

Object Pascal allows parameters of the same type to be listed together, separated by commas, and followed with a single data type (more params of different data types can follow, after a semi-colon). The default for parameters is by value. For by reference, add var in front of the parameter. Object Pascal also offers constant parameters where you add const in front of the parameter. A constant parameter is like a local constant or read-only parameter the compiler can optimize. You cannot assign a value to a constant parameter, nor can you pass one as a var parameter to another routine.

function Add(a, b: integer) : integer; 
begin
  Result := a + b;
end;
 
procedure ReplaceTime(var pDT: TDateTime; const pNewDT: TDateTime);
begin
end;
-Collapse +Expand 78. Delphi Report Tools Overview
 

Rave Reports comes closest to a Delphi standard now but historically there has been no real standard in Delphi development. Do-it-yourself developers sometimes like to use TPrinter for very simple reports. ReportSmith was bundled with the first few versions of Delphi.

Delphi has offered many embedded VCL component report options. Quick Reports has been a part of Delphi since Delphi 2.0 and has been the default report writer for many Delphi developers. Ace Reporter, ReportBuilder and Rave Reports are also very popular. During the time of Kylix, FastReports was popular because of it's cross-platform nature.

-Collapse +Expand 79. Delphi String Concatenation (+)
 

Use the + operator to concatenate two strings. Use IntToStr to convert an integer to a string and FloatToStr to convert a floating point number to a string.

var 
  FirstName : String; 
  LastName : String;
begin 
  FirstName := 'Mike'; 
  LastName := 'Prestwood';
  ShowMessage('Full name: ' + FirstName + ' ' + LastName);
  
  ShowMessage(FloatToStr(3.2));
end;
-Collapse +Expand 80. Delphi Unary Operators
 

An operation with only one operand (a single input). In Object Pascal, a unary operator always precedes its operand (for example, -B), except for ^, which follows its operand (for example, P^). The Delphi unary operators are +, -, and ^ (pointer).

The TYPE operator is also a unary operator and is�evaluated at compile time. The TYPE operator returns the size in bytes of the operand,

-Collapse +Expand 81. Delphi Variables (var x: Integer = 0;)
 

Declare global variables in the interface section of a unit, variables declared within the implementation section (but not within a method) have a scope limited to the unit. You declare local variables in a var block outside (above) your begin..end code block. You cannot declare variables in-line (inside begin..end). You can initialize global and unit variables but you cannot initialize local variables. Delphi offers many variable types. Some common variable types include String, WideString, PCharInteger, Boolean, Single, Double, Pointer, and Variant.

procedure SomeProcedure;
var
  Fullname: String;
  Age: Integer;
  X, Y, Z: Double;
  MyArray: array [1..100] of Char;
begin
end;
 
//You can initialize global variables.
var
  ClickCounter: Integer = 0;



Topic: Language Details

-Collapse +Expand 82. Associative Arrays in Delphi/Object Pascal (Use TStringList)
 

TStringList Example
Object Pascal doesn't have a native associative array, but you can use a TStringList the same way. (Alternatively, search the Internet for TStringHash and THashedStringList classes for implementations of a true associative array).

var
  StateList : TStringList;
begin
  StateList := TStringList.Create; //Create list.
  //Add values comma separated.
  StateList.CommaText := 'CA=California, AR=Arizona';
  StateList.CommaText := StateList.CommaText + ', FL=Florida';
  //Also, can add individually.
  StateList.Add('NV=Nevada');
  //Use it.
  ShowMessage('FL is ' + StateList.Values['FL']);
end;
-Collapse +Expand 83. Delphi Associative Array (TStringList Assoc Array)
 

Object Pascal doesn't have a native associative array, but you can use a TStringList the same way. (Alternatively, search the Internet for TStringHash and THashedStringList classes for implementations of a true associative array).

var
  StateList : TStringList;
begin
StateList := TStringList.Create; 
  StateList.CommaText := 'CA=California, FL=Florida';
  ShowMessage('FL is ' + StateList.Values['FL']);
end;
-Collapse +Expand 84. Delphi Comparison Operators (=, <>)
 

Common comparison operators:

= equal
<> not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

//Does Delphi evaluate the math correctly? Yes!
//Refer to math.pas MaxSingle for more info.
if (0.1 + 0.1 + 0.1 = 0.3) then
ShowMessage('correct')
else
ShowMessage('not correct')
-Collapse +Expand 85. Delphi Custom Routines (procedure, function)
 

Delphi is a hybrid language so you can create either class methods (functions and procedures) or you can create global functions and procedures. When a function or procedure is part of a class, it is a class method.

[function/procedure] RoutineName : ReturnType;

As with C++, your custom routine must come before it's first usage or you have to prototype it in the Interface section.

Note: Contrast Delphi with Delphi Prism which is an OOP language (everything is within a class). Both Delphi and Delphi Prism are based on Object Pascal but implement OOP features differently and have some syntax differences too.

procedure SayHello(pName: String);
begin
  ShowMessage('Hello ' + pName);
end;
 
function Add(p1, p2 : Double): Double;
begin
  Result := p1 + p2;
end;
-Collapse +Expand 86. Delphi Inlining (Inline)
 

Delphi introduced developer defined function and procedure inlining with Delphi 2005. Use the inline keyword to tell the compiler to inline a routine. Since Delphi will always inline the routine, make sure you test for speed because inlining a routine can lead to slower code under some circumstances.

function Add(a, b: Integer): Integer; inline;
begin
end;
-Collapse +Expand 87. Delphi LeftStr
 

Delphi LeftStr

Uses StrUtils;
ShowMessage(LeftStr('Prestwood', 3));
-Collapse +Expand 88. Delphi Overloading (overload)
 

Object Pascal

  • Operator - Yes. But not Pascal.
  • Method - Yes.  
function Add(a, b: integer): Integer;  overload;
begin
Result := a+b;
end;
function Add(const msg: String; a, b: integer): String; overload;
begin
  Result := msg + IntToStr(a+b);
end;
-Collapse +Expand 89. Delphi Pointers
 

Although pointer data types in Delphi coding are less important and not required for most general coding, Delphi fully supports developer defined pointers. Use a carrot (^) to declare a pointer data type. Use the @ operator or Addr function to return the current address of a variable.

//Declare a pointer of type integer.
PCounter : ^Integer;
  
//Assign a value to the location of a pointer.
//Also known as dereferencing.
PCounter^ := 8;
  
//Assign address of A to B.
PointerB := @PointerA;  //or...PointerB := Addr(PointerA);
-Collapse +Expand 90. Delphi Self Keyword (Self)
 

Within the implementation of a method, the identifier Self references the object in which the method is called. The Self variable is an implicit parameter for each object method.
A method can use this variable to refer to its owning class.

ShowMessage('Self=' + Self.ClassName);
-Collapse +Expand 91. Example: Using Sets in Borland Delphi
 

Simple example of using sets in Delphi. Sets are similar to arrays and are convenient to use with 'in'.

procedure TForm1.Button7Click(Sender: TObject);
var
ValidStrings: Set of Char;
begin
ValidStrings := ['Y', 'N', 'X'];
  If 'Y' in ValidStrings then
ShowMessage('Yes, Y is valid');
end;



Topic: OOP

-Collapse +Expand 92. Delphi Abstraction (abstract, override)
 

Delphi for Win32 supports abstract class members using the abstract keyword. You can even instantiate instances of a class that contains abstract members. Then you override each abstract member in a descendant class with Override. Delphi does not support setting an entire class as abstract. You can create an abstract class (a class with one or more abstract methods), but there is no way to tell the compiler to not allow the instantiation of the abstract class. Delphi does not support abstract member properties directly. To implement an abstract properity, make use of abstract methods. That is, you can read a GetPropertyX abstract function and write to a SetPropertyX abstract procedure. In effect, creating  an abstract property.

TCyborg = class(TObject)
public
  procedure Speak(pMessage: String); virtual; abstract;
  procedure Walk; virtual; abstract;
end;
 
TSeries600 = class(TCyborg)
public
  procedure Speak(pMessage: String); override;
  procedure Walk; override;
end;
-Collapse +Expand 93. Delphi Base Class (TObject)
 

In Delphi programming language (Object Pascal), all classes ultimately inherit from the base class TObject.

//Specify both namespace and class:
TCyborg = class(System.TObject)
end;
  
//Use shortcut alias:
TCyborg = class(TObject)
end;
  
//None, default is System.TObject
TCyborg = class
end;
-Collapse +Expand 94. Delphi Class Helpers (class helper for)
 

Delphi allows you to extend an existing class without using inheritance. Buggy in 2005 and not officially supported but stable and usable in 2006 and above. You declare a class helper similiar to how you declare a class but use the keywords class helper for.

  • You can name a helper anything.
  • Helpers have access only to public members of the class.
  • You cannot create an object instance directly from a class helper.
  • self refers to the class being helped.
TCyborg = class(TObject)
public
  FCyborgName: String;
end;
  
TCyborgHelper = class helper for TCyborg
  procedure ShowClassName;
end;
-Collapse +Expand 95. Delphi Class Members (Class)
 

Object Pascal supports static methods, but not static member fields. For static member fields, use traditional Pascal-like global variables. Since Object Pascal is a hybrid language, you can use global functions and data so the need for class methods is diminished but still useful. Delphi 1-7: All classes in a unit are friendly (see eachother's private members), some developers like to put each class in it's own unit and reserve putting multiple classes in the same unit until they wish to implement friendly classes. Delphi 2005+: New strict keyword allows you to indicate friendly.

type
TMyUtils = class(TObject)
public
class function MyStaticMethod: Integer;
end;

In implimentation:

class function TMyUtils.MyStaticMethod: Integer;
-Collapse +Expand 96. Delphi Class..Object (class..end..Create)
 

Declare your class in the Interface section. Then implement the class in the Implementation section.

//Interface section:
TCyborg = class(TObject)
public
procedure IntroduceYourself;
end;
 
//Implementation section;
procedure TCyborg.IntroduceYourself;
begin
ShowMessage('Hi, I do not have a name yet.');
end;
 
//Some event like a button click:
var
T1: TCyborg;
begin
T1 := T1.Create;
T1.IntroduceYourself;
  FreeAndNil(T1);      //Be sure to clean up!
end;
-Collapse +Expand 97. Delphi Constructors (constructor)
 

In Delphi, use the constructor keyword to signify which method or methods are constructors for a class. It is traditional but not required to use a procedure called Create.

In addition to having multiple named constructors, you can overload constructors.

//Interface section.
TCyborg = class(TObject)
public
  constructor Create;
end; 

Then implement the class constructor in the Implementation section.

constructor TCyborg.Create;
begin
  inherited;  //Call the parent Create method
end;
-Collapse +Expand 98. Delphi Destructor (Free or FreeAndNil)
 

Object Pascal uses a standard virtual destructor named Destroy which is called by the standard Free method. All objects are dynamic, so you need to call MyObject.Free method or the FreeAndNil(MyObject) routine for each object you create.

var
MyObject: TObject;
begin
MyObject := TObject.Create;
 
  //Use it...
  
  MyObject.Free
  //Or use...FreeAndNil(MyObject);
end;
-Collapse +Expand 99. Delphi Inheritance (=class(ParentClass))
 

In Delphi, you use the class keyword followed by the parent class in parens. If you leave out the parent class, your class inherits from TObject.

In the following example, a terminator T-600 is-an android. 

TAndroid = class
end;
 
T-600 = class(TAndroid)
end;
-Collapse +Expand 100. Delphi Inheritance-Multiple (Not Supported)
 

Delphi does not support multiple implementation inheritance. Each class can have only one parent class (a single inheritance path). In Delphi, you can use multiple interface usage to design in a multiple class way horizontally in a class hierarchy.

-Collapse +Expand 101. Delphi Interfaces (IInterface, TInterfacedObject)
 

You specify an interface in the type block just like you do for a class but you use the interface keywoard instead of the class keyword and in the interfaces section only. Since interfaces, by definition, do not have any implementation details, all you do is specifiy it in the type block.

//Language interface:
//Interface section of unit.
IHuman = Interface(IInterface)
  //Specify interface methods and properties here.

end;
  
TCyborg = class(TInterfacedObject)
end;
  
TCyborgHuman = class(TCyborg, IHuman)
//Specify each here and implement in
//implementation section.
end;
-Collapse +Expand 102. Delphi Member Field
 

In Delphi, it is common to start all member fields with "F" as in FName and FAge. You can initialize the value of member fields. Delphi member fields do not support static data. The workaround is to use the hybrid nature of Delphi and use a unit variable (a variable declared in the implementation section of a unit).

TCyborg = class(TObject)
private
  FSerialNumber: String='A100';
public
FCyborgName: String;
FCyborgAge: Integer=0;

  FSeriesID: Integer=100;
end;
-Collapse +Expand 103. Delphi Member Method (procedure, function)
 

Delphi uses the keywords procedure and function. A procedure does not return a value and a function does.

//Interface section:
TCyborg = class(TObject)
public
  procedure IntroduceYourself;
end;
 
//Implementation section;
procedure TCyborg.IntroduceYourself;
begin
  ShowMessage('Hi, I do not have a name yet.');
end;
 
//Some event like a button click:
var
  T1: TCyborg;
begin
  T1 := T1.Create;
  T1.IntroduceYourself;
end;
-Collapse +Expand 104. Delphi Member Modifiers
 

Specify Delphi member modifiers as follows:

reintroduce; overload; [binding modifier]; [calling convention]; abstract; [warning]

The binding modifiers are virtual, dynamic, or override. The calling conventions are register, pascal, cdecl, stdcall, or safecall. The warnings are platform, deprecated, or library. Additional directives include reintroduce, abstract, class, static, overload, and message.

TCyborg = class(TObject)
public
  procedure Speak(pMessage: String); virtual;
end;
 
TSeries888 = class(TCyborg)
public
  procedure Speak(pMessage: String); override;
end;
-Collapse +Expand 105. Delphi Member Property (property..read..write)
 

Delphi uses a special property keyword to both get and set the values of properties. The read and write keywords are used to get and set the value of the property directly or through an accessor method. For a read-only property, leave out the write portion of the declaration.

You can give properties any visibility you wish (private, protected, etc). It is common in Delphi to start member fields with "F" ("FName" in our example) and drop the "F" with properties that manage member fields ("Name" in our example).

TCyborg = class(TObject)
private
  FCName: String;
public
  property CyborgName: String read FCName write FCName;
end;
-Collapse +Expand 106. Delphi Member Visibility
 

Up until D2005, private and protected were not implemented strictly. Starting with D2005, a traditional strict versions of OOP are supported using the strict keyword. OO purist will want you to use strict private over private and strict protected over protected. I suggest you follow that advice until you both fully understand the differences and have a specific need. Delphi offers a special published specifier which is the same as public members but runtime type information (RTTI) is generated.

TCyborg = class(System.Object)
private
//Don't use accept when you really want private friendly members.
strict private
//Use as your default private members.
  FName: String;
protected
//Don't use accept when you really want protected friendly members.
strict protected
//Use as your default protected members.
public
  

published
  //RTTI Info

end;
-Collapse +Expand 107. Delphi Overriding (virtual, override)
 

In Delphi, you specify a virtual method with the virtual keyword in a parent class and replace it in a descendant class using the override keyword. Call Inherited in the descendant method to execute the code in the parent method.

TRobot = class(TObject)
public
procedure Speak; virtual;
end;
  
TCyborg = class(TRobot)
procedure Speak; Override;
end;
-Collapse +Expand 108. Delphi Polymorphism
 
-Collapse +Expand 109. Delphi Sealed class (sealed, final)
 

With Delphi, use the sealed keyword to prevent a class from being inherited from and use the final keyword to prevent a method from being overridden.

type
  Robot = class sealed(TObject)
public
  procedure Speak(pSentence: String); virtual; final;
end;



Topic: Using Data

-Collapse +Expand 110. Application.ProcessMessages
 

I always found the sleep command in ObjectPAL very useful. The following code does about the same thing in Delphi. It makes use of GetTickCount which is a Win32 API call that retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days.

procedure TUtils.Delay(MillisecondsDelay: Integer);
var
   FirstTickCount: LongInt;
begin
   FirstTickCount := GetTickCount;
   repeat 
       Application.ProcessMessages;
   until ((GetTickCount-FirstTickCount) >= Longint(MillisecondsDelay));
end;



Group: C# (Visual C# & VS.Net)





Topic: C#

-Collapse +Expand 111. C# Empty String Check (String.IsNullOrEmpty)
 

The .Net framework offers a static method in the string class: String.IsNullOrEmpty.

String s;
 
s = "";
//s = null; //Uncomment to test 2nd case.
 
if (String.IsNullOrEmpty(s))
{
  MessageBox.Show("empty string");
}



Topic: Tool Basics

-Collapse +Expand 112. C# Assignment (=)
 

Languages Focus: Assignment

Common assignment operators for languages include =, ==, and :=. An assignment operator allows you to assign a value to a variable. The value can be a literal value like "Mike" or 42 or the value stored in another variable or returned by a function.

C# Assignment

C# uses = for it's assignment operator.

int Age;
string FullName;
  
Age = 42;
FullName = "Randy Spitz";
-Collapse +Expand 113. C# Case Sensitivity (Yes)
 

C# is case sensitive. The following does NOT:

messagebox.Show("hello");  //Does not work!

The first time you type any other case for commands or variables, VS.Net will change it to the accepted or defined case. For example, if you type messagebox.show it is converted to MessageBox.Show. Once corrected, you can break it again by editing MessageBox to messagebox and the compiler will give you an error.

The following code works:

MessageBox.Show("hello");
-Collapse +Expand 114. C# Comparison Operators (==, !=)
 

General Info: Round Floating Point Numbers

When comparing floating point numbers, make sure you round to an acceptable level of rounding for the type of application you are using.

Languages Focus: Comparison Operators

A comparison operator compares two values either literals as in "Hello" and 3 or variables as in X and Counter. Most languages use the same operators for comparing both numbers and strings. Perl, for example, uses separate sets of comparison operators for numbers and strings.

C# Comparison Operators

Common comparison operators:

== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

//Does C# evaluate the math correctly? No!
if (.1 + .1 + .1 == .3)
MessageBox.Show("correct");
else
MessageBox.Show("not correct");
-Collapse +Expand 115. C# Constants (const)
 

In C#, you define constants with the const keyword.

All constants are part of a class (no global constants) but you can make a constant public and have access to it so long as you have added the class to the project (even without creating the class as if they were static, but you cannot use the static keyword).

Constants must be of an integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration, or a reference to null.

public class Convert : Object
{
  public const string kName = "Mike";
 
  //You can declare multiple of the same type too:
  const Double kFeetToMeter = 3.2808, kMeterToFeet = .3048;
}
-Collapse +Expand 116. C# Deployment Overview
 

C# projects require the .Net framework and any additional dependencies you've added such as Crystal Reports.

In Visual Studio.Net, you can create a Setup and Deployment project by using any of the templates available on the New Project dialog (Other Project Types).

In addition, C# projects also support ClickOnce which brings the ease of Web deployment to Windows Forms and console applications. To get started, right click on your solution in the Solution Explorer, click Properties then select the Security tab. 

In addition, you can use any of the many free and commercially available installation packages.

-Collapse +Expand 117. C# File Extensions
 

Common source code file extensions include:

  • .SLN - Solution File. Contains solution specific information such as links to the projects within this solution.
  • .CSPROJ - C# Project File. Contains project specific information.
  • .CS - C# source file.
  • .Designer.CS - C# form file (a text resource file).
//Sample code snippet from the .csproj project file:
<ItemGroup>
  <Compile Include="Cyborg.cs" />
  <Compile Include="Cyborg600.cs" />
  <Compile Include="Form1.cs">
    <SubType>Form</SubType>
  </Compile>
  //...
-Collapse +Expand 118. C# Multiple Line Comment (// or /* */)
 

Commenting Code
C# uses "//" for a single line comment and /* */ for a multiple line comment.

//Single line comment.

/*
Multiple line
comment.
*/
-Collapse +Expand 119. C# Overview and History
 

Language Overview: C# is an OOP language (no global functions or variables) and is type-safe. You code using a fully OOP approach (everything is in a class).

Target Platforms: C# is most suitable for creating any type of application that runs on the .Net platform. This includes desktop business applications using WinForms and websites using WebForms.

-Collapse +Expand 120. C# Report Tools Overview
 

For WebForm applications the client target is the browser (a document interfaced GUI), a common solution is to simply output an HTML formatted page with black text and a white background (not much control but it does work for some situations). For WinForm applications, Crystal Reports is still a popular choice with C# developers because it has been bundled with many Microsoft products, it's overall popularity, and compatibility with many different development tools.

-Collapse +Expand 121. C# String Concatenation (+)
 

C# String Concatenation

C# performs implicit casting of numbers to strings. To concatenate two strings, a string to an integer, or a string to a floating point number, use the + operator. For example, to convert a floating point number to a string just concatenate an empty string to the number as in "" + 3.2.

Alternatively, you can use the System.Text.StringBuilder class which frequently but not always provides faster code.

String FirstName;
String LastName;
Int16 Age;
FirstName = "Mike";
LastName = "Prestwood";
Age = 43;
Console.WriteLine(FirstName + " " + LastName + " is " + Age + ".");
  
//Implicit casting of numbers.
//
//This fails:
//MessageBox.Show(3.3);
//
//This works:
MessageBox.Show("" + 3.3); 
-Collapse +Expand 122. C# Variables (Int16 x=0;)
 

C++, Java, and C# all use C-like variable declaration.

C# has C-like variable declaration and although variables are case sensitive, VS.Net will auto-fix your variable names to the defined case.

C# offers many variable types. Some common types used include short, intlong, float, double, decimal, Int16, UInt16, Int32, Int64, string, and bool.

You can also specify the value when you declare a variable as in:

String FirstName = "Mike";
String LastName = "Prestwood";
Int16 Age = 42;
string FullName;
int16 Age;
double Weight;
 
FullName = "Mike Prestwood";
Age = 32;
Weight = 154.4;



Topic: Language Basics

-Collapse +Expand 123. C# Code Blocks ({ })
 

For C#, I prefer to put the opening { and the closing } on their own line (as opposed to C++, Java, and JavaScript where I put the opening bracket at the end of the first line.

int DoSomething()
{
 int a = 1;
 int b = 2;
 return a + b;
}
-Collapse +Expand 124. C# Custom Routines
 
ReturnType RoutineName()

 

Note: C# requires () in both the function declaration, and when it's invoked.

void SayHello(String pName)
{
MessageBox.Show("Hello " + pName);
}
int Add(int a, int b) 
{
return a + b;
}
-Collapse +Expand 125. C# Development Tools
 

Languages Focus: Development Tools

Primary development tool(s) used to develop and debug code.

C# Development Tools

Microsoft Visual C# and the full version of Microsoft Visual Studio.Net are the current primary tools. CodeGear does have C#Builder but it's not a primary tool currently and development on the tool has slowed in recent years.

-Collapse +Expand 126. C# End of Statement (;)
 

C# uses a semicolon ";" as an end of statement specifier and you can put multiple statements on a single line of code if you wish as well as split a single statement into two or more code lines.

Console.WriteLine("Hello1");
Console.WriteLine("Hello2");
Console.WriteLine("Hello3");

//Same line works too:
Console.WriteLine("Hello4"); Console.WriteLine("Hello5");
 
//Two or more lines works too: 
Console.
  WriteLine
("Hello6");

-Collapse +Expand 127. C# Exception Trapping (try...catch...finally)
 

C# uses a try...catch...finally statement to trap for errors.

try {}
catch {}
finally {}
try
{
int y = 0;
y = 1 / y;
}
catch
{
MessageBox.Show("you cannot divide by zero");
}
-Collapse +Expand 128. C# If Statement (if..else if..else)
 

Use () around evaluation with no "then".

Boolean x = true;


if (x)
{
MessageBox.Show("hello");
}
else if (x==false)
{
MessageBox.Show("goodbye");
}
else
{
  MessageBox.Show("what?");
}
-Collapse +Expand 129. C# Inheritance (: ParentClass)
 

Simple syntax example of class inheritance.

In the following example, a terminator T-600 is-an android. 

public class Android
{
}
 
public class T-600 : Android
{
}
-Collapse +Expand 130. C# Literals (quote)
 

Literals are quoted as in "Prestwood". If you need to embed a quote use a slash in front of the quote as in \"

Console.WriteLine("Hello");
Console.WriteLine("Hello \"Mike\".");
 
//Does C# evaluate this simple
//floating point math correctly? No! 
if ((0.1 + 0.1 + 0.1) == 0.3)
{
MessageBox.Show("Correct");
}
else
{
MessageBox.Show("Not correct");
}
-Collapse +Expand 131. C# Logical Operators
 

Same as C++ and Java. C# logical operators:

& and, as in this and that No Short Circuit
&& and, as in this and that short circuits
| or, as in this or that No Short Circuit
|| or, as in this or that short circuits
! Not, as in Not This
^ either or, as in this or that but not both

//Given expressions a, b, c, and d:
if !((a && b) && (c || d)) 
{
  //Do something.
}
-Collapse +Expand 132. C# Overloading (implicit)
 

C# Overloading

  • Operator - Yes.
  • Method - Yes.
-Collapse +Expand 133. C# Parameters
 

Defining
In C# the data type of each parameter must be specified, even if adjacent parameters are of the same type.

integer Add(int a, int b)

-Collapse +Expand 134. C# Substring
 

C# Substring

Above returns "abcd" on a string literal. You can, of course, use VarName.Substring(0, 4).

Console.WriteLine("abcdefgh".Substring(0, 4));
-Collapse +Expand 135. C# Unary Operators
 

An operation with only one operand (a single input). The following are the C# unary operators: +, -, !, ~, ++, --, true, or false.




Topic: Language Details

-Collapse +Expand 136. C# Associative Array (Dictionary)
 

General Info: Associative Array

A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'

Languages Focus: Associative Array

Associative arrays are also known as a dictionary or a hash table in other languages.

C# Associative Array

//using System.Collections.Generic;
 
Dictionary <String, String> airports = new Dictionary <String, String>();
airports.Add("LAX", "Los Angeles"); 
airports.Add("SFO", "San Francisco");
airports.Add("SAN", "San Diego");
MessageBox.Show(airports["LAX"]);
-Collapse +Expand 137. C# Inlining (Automatic)
 

In C#, inlining is automatically done for you by the JIT compiler for all languages and in general leads to faster code for all programmers whether they are aware of inlining or not.

-Collapse +Expand 138. C# Pointers
 

Although pointer data types in C# coding are less important than in other languages such as C++, C# does support developer defined pointers. Use the * operator to declare a pointer data type. Use the & operator to return the current address of a variable.

In .Net managed coding the use of pointers is not safe because the garbage collector may move memory around. To safely use pointers, use the unsafe keyword.

C++/CLI has more extensive support for pointers than C#. If you have needs that go beyond what C# offers, you can code in C++/CLI and add it to your project.

//Declare a pointer of type integer.
Integer *PCounter;



Topic: OOP

-Collapse +Expand 139. C# Abstraction (abstract, override)
 

C# supports abstract class members and abstract classes using the abstract modifier. An abstract class is a class with one or more abstract members and you cannot instantiate an abstract class. However, you can have additional implemented methods and properties. An abstract member is either a method (implicitly virtual), property, indexer, or event in an abstract class. You can add abstract members ONLY to abstract classes using the abstract keyword.

abstract public class Cyborg : System.Object
{
  abstract public void Speak(string pMessage);
}
public class Series600 : Cyborg
{
  public override void Speak(string pMessage)  
  {
    MessageBox.Show(pMessage);  
  }
}
-Collapse +Expand 140. C# Access Modifiers
 

In C#, you specify each class and each class member's visibility with an access modifier. The C# access modifiers are the traditional public, protected, and private plus the two additional .Net modifiers internal and protected internal.

Internal indicates members are accessible from types in the same assembly. Protected internal indicates members are accessible from types in the same assembly as well as descendant classes. OO purist might object to internal and protected internal and I suggest you choose private, protected, or public over them until you both fully understand them and have a need that is best suited by them.

The default for class and class members is Internal (members are accessible from types in the same assembly). This is different than with interfaces where the default for an interface is Internal but an interface's members are always public -- which makes sense but is noteworthy.

With both classes and interfaces, if you make a class public, the members are public. This applies to the other access modifiers too. For example, if you make a class protected, the members default access modifiers are protected.

public class Cyborg
{
private String FName;
}
-Collapse +Expand 141. C# Base Class (System.Object)
 

In C#, the Object keyword is an alias for the base System.Object class and is the single base class all classes ultimately inherit from.

//Specify both namespace and class:
public class Cyborg : System.Object 
{ }
  
//Use shortcut alias:
public class Cyborg : Object 
{ }
  
//None, default is System.Object
public class Cyborg
{ }
-Collapse +Expand 142. C# Class..Object (class...new)
 

In C#, you use the class keyword to specify a class and you signify its parent with a colon and the name of the parent class. When you instantiate an object from a class, you use the new keyword.

Define class:

public class Cyborg : System.Object
{
public virtual void IntroduceYourself()
{
MessageBox.Show("Hi, I do not have a name yet.");
}
}

Create object from class:

Cyborg T1 = new Cyborg();
T1.IntroduceYourself();
//No need to clean up with managed classes.
//The garbage collector will take care of it.
-Collapse +Expand 143. C# Constructors (Use class name)
 

In C#, a constructor is called whenever a class or struct is created. A constructor is a method with the same name as the class with no return value and you can overload the constructor. If you do not create a constructor, C# will create an implicit constructor that initializes all member fields to their default values.

Constructors can execute at two different times. Static constructors are executed by the CLR before any objects are instantiated. Regular constructors are executed when you create an object.

public class Cyborg
{
public string CyborgName;
  
  //Constructor.
  public Cyborg(string pName)
{
CyborgName = pName;
}
}
-Collapse +Expand 144. C# Finalizer (~ClassName)
 

Use a destructor to free unmanaged resources. A destructor is a method with the same name as the class but preceded with a tilde (as in ~ClassName). The destructor implicity creates an Object.Finalize method (you cannot directly call nor override the Object.Finalize method).

In C# you cannot explicitly destroy an object. Instead, the .Net Frameworks garbage collector (GC) takes care of destroying all objects. The GC destroys the objects only when necessary. Some situations of necessity are when memory is exhausted or you explicitly call the System.GC.Collect method. In general, you never need to call  System.GC.Collect.

class Cyborg {
public:
//Destructor for class Cyborg.
~Cyborg();
  {
  //Free non-managed resources here.
  }
};
-Collapse +Expand 145. C# Inheritance-Multiple (Not Supported)
 

C# does not support multiple implementation inheritance. Each class can have only one parent class (a single inheritance path). In C#, you can use multiple interface usage to design in a multiple class way horizontally in a class hierarchy.

-Collapse +Expand 146. C# Interfaces (interface)
 

Classes and structs can inherit from interfaces in a manner similar to how classes can inherit a base class or struct, but a class or struct can inherit more than one interface and it inherits only the method names and signatures, because the interface itself contains no implementations.

class MyClass: IMyInterface
{  
  public object Clone()
{
return null;
}

// IMyInterface implemented here...
}
interface IMyInterface
{
  bool IsValid();
}
-Collapse +Expand 147. C# Member Field
 

In C# you can set the visibility of a member field to any visibility: private, protected, public, internal or protected internal.

You can intialize a member field with a default when declared. If you set the member field value in your constructor, it will override the default value.

Finally, you can use the static modifier (no instance required) and readonly modifier (similar to a constant).

public class Cyborg : System.Object
{
  private string serialNumber = "A100";
 
  public string cyborgName; 
  public int cyborgAge = 0;
  public static readonly int seriesID = 100;
}
-Collapse +Expand 148. C# Member Method
 

In C# you can set the visibility of a member field to any visibility: private, protected, public, internal or protected internal. You can intialize a member field with a default when declared. If you set the member field value in your constructor, it will override the default value. Finally, you can use the static modifier (no instance required) and readonly modifier (similar to a constant).

Define class:

public class Cyborg : System.Object
{
public virtual void IntroduceYourself()
{
MessageBox.Show("Hi, I do not have a name yet.");
}
}

Create object from class:

Cyborg T1 = new Cyborg();
T1.IntroduceYourself();
-Collapse +Expand 149. C# Member Modifiers
 

The method modifiers are abstract, extern, new, partial, sealed, virtual, and override. Specify C# member modifiers as follows:

abstract SomeMethod() {..}

The field modifiers are const, readonly, static, volatile. Specify field modifiers as follows:

readonly int MyAge;

-Collapse +Expand 150. C# Member Property (no (), get, set)
 

In C#, parens indicate a method and the lack of parens indicate a property. You use special get and set methods to both get and set the values of properties. For a read-only property, leave out the set method. The value keyword is used to refer to the member field. Properties can make use of any of the access modifiers (private, protected, etc). It is common to use a lowercase member names for member fields ("name" in our example) and uppercase properties to manage member fields ("Name" in our example).

public class Cyborg : System.Object
{
  private string cyborgName;
 
  public string CyborgName
  {
  get {return cyborgName;}
  set {cyborgName = value;}
  }

}
-Collapse +Expand 151. C# Overriding (virtual, override)
 

Method overriding allows you to define or implement a virtual method in a parent class and then replace it in a descendant class. In C#, you specify a virtual method with the virtual keyword in a parent class and replace it in a descendant class using the override keyword.

class Robot
{
  public virtual void Speak()
  {
  }
}

class Cyborg:Robot
{
  public override void Speak()
  {
  }
}
-Collapse +Expand 152. C# Partial Classes (partial)
 

C# uses the keyword partial to specify a partial class. All parts must be in the same namespace.

A partial class, or partial type, is a class that can be split into two or more source code files and/or two or more locations within the same source file. Each partial class is known as a class part or just a part. Logically, partial classes do not make any difference to the compiler. The compiler puts the class together at compile time and treats the final class or type as a single entity exactly the same as if all the source code was in a single location.

You can use them for many things including to separate code generator code, organize large classes, divice a class up so you can split ownwership among multiple developers, have different versions of the same class, and to utilize multiple languages with a single class.

class partial Cyborg: System.Object
{
}
-Collapse +Expand 153. C# Polymorphism
 
-Collapse +Expand 154. C# Prevent Derivation (sealed)
 

With C#, use the sealed keyword to prevent a class from being inherited from and to prevent a method from being overridden.

A method marked sealed must override an ancestor method. If you mark a class sealed, all members are implicitly not overridable so the sealed keyword on members is not legal.

public class Machine : System.Object
{
public virtual void Speak(String pSentence)
{
MessageBox.Show(pSentence);
}
}

public class Robot : Machine
{
public sealed override void Speak(String pSentence)
{
MessageBox.Show(pSentence);
}
}
  
public sealed class Cyborg : Robot
{
}
-Collapse +Expand 155. C# Self Keyword (this)
 

To refer to the current instance of a class, use the this keyword. The this keyword provides a way to refer to the specific instance in which the code is currently executing. It is particularly useful for passing information about the currently executing instance.

The this keyword is also used as a modifier of the first parameter of an extension method.

You cannot use this with static method functions because static methods do not belong to an object instance. If you try, you'll get an error.

-Collapse +Expand 156. C# Static Members (static)
 

C# supports both static members and static classes using the static keyword. You can add a static method, field, property, or event to an existing class. Also, you can designate a class as static and the compiler will ensure all members in that class are static. You can add a constructor to a static class to initialize values.

The CLR automatically loads static classes with the program or namespace.

//Static Class Example
public static class MyStaticClass
{
  //Static Method Example
  public static void MyStaticMethod()
{
// static method code
}
}
-Collapse +Expand 157. VB Classic Prevent Derivation (Not Supported)
 

VB Classic supports a form of single level inheritance where you, in essence, create an abstract class and then implement it in one or more classes that inherit from the abstract class. However, you cannot have any further descendant classes so "prevent derivation" is implemented by design of this simple inheritance model.




Group: VB.Net Language





Topic: VB.Net

-Collapse +Expand 158. VB.Net Case Sensitivity (No)
 

VB.Net is not case sensitive. If you type any other case for commands or variables, VB.Net will change it to the accepted or defined case. For example, if you type messagebox.show it is converted to MessageBox.Show.

The following code works:

MessageBox.Show("hello")
-Collapse +Expand 159. VB.Net Code Blocks (End Xxx)
 

VB.Net, like VBClassiccode blocks, are surrounded by statement ending keywords that all use End such as End Class, End Sub, End Function, End If, and End If.

Public Class Dog
End Class
 
Protected Sub MySub
End Sub
  
Public Shared Function MySharedFunction() As Integer
MySharedFunction = 12345
End Function
 
If x Then
End If
-Collapse +Expand 160. VB.Net Empty String Check (String.IsNullOrEmpty)
 

The .Net framework offers a static method in the string class: String.IsNullOrEmpty.

Dim s As String 
  
's = "" 'Uncomment to test 2nd case.
  
If String.IsNullOrEmpty(s) Then
  MessageBox.Show("hello")
End If
-Collapse +Expand 161. VB.Net File Extensions
 

Common source code file extensions include:

  • .SLN - Solution File. Contains solution specific information such as links to the projects within this solution.
  • .VBPROJ - VB.Net Project File. Contains project specific information.
  • .VB -VB.Net source file.
  • .Designer.VB -VB.Net form file (a text resource file).
//Sample code snippet from the .vbproj project file:
<ItemGroup>
  <Compile Include="Cyborg.vb" />
  <Compile Include="Form1.vb">
    <SubType>Form</SubType>
  </Compile>
  //...
-Collapse +Expand 162. VB.Net If Statement (If..ElseIf..Else..End If)
 

Same as VB classic.

If x Then
MessageBox.Show("hello")
ElseIf Not x Then
MessageBox.Show("goodbye")
Else
MessageBox.Show("what?")
End If
-Collapse +Expand 163. VB.Net Left of Substring (Left or Substring)
 

The above usage of Left and Substring are equivalent.

Left is a traditional VB approach popular with developers moving from VB Classic to VB.Net. Substring is considered the .Net way of doing string manipulation.

Dim FullName
FullName = "Prestwood"
Console.WriteLine("Hello " + Left(FullName, 4))
Console.WriteLine("Hello " + FullName.Substring(0, 4))
-Collapse +Expand 164. VB.Net Parameters (ByVal, ByRef)
 

By Reference or Value
For parameters, you can optionally specify ByVal or ByRef. ByVal is the default if you don't specify which is changed from VB Classic (in VB Classic, ByRef was the default).

Private Function Add(ByRef a As Integer, _
ByRef b As Integer) As Integer
  Add = a + b
End Function



Topic: Tool Basics

-Collapse +Expand 165. VB.Net Assignment (=)
 

Languages Focus: Assignment

Common assignment operators for languages include =, ==, and :=. An assignment operator allows you to assign a value to a variable. The value can be a literal value like "Mike" or 42 or the value stored in another variable or returned by a function.

VB.Net Assignment

VB.Net uses = for it's assignment operator.

Dim Age As Integer
Dim FullName As String
  
FullName = "Randy Spitz"
Age = 38
-Collapse +Expand 166. VB.Net Comments (' or REM)
 

Languages Focus: Comments

Commenting code generally has three purposes: to document your code, for psuedo coding prior to coding, and to embed compiler directives. Most languages support both a single line comment and a multiple line comment. Some languages also use comments to give instructions to the compiler or interpreter.

VB.Net Comments

Commenting Code
VB.Net, like all the VB-based languages, uses a single quote (') or the original class-style basic "REM" (most developers just use a quote). VB.Net does NOT have a multiple line comment.

'Single line comment.

REM Old school single line comment.

 


-Collapse +Expand 167. VB.Net Constants (Const kPI Double = 3.1459)
 

In VB.Net, you define constants with the Const keyword.

All constants are part of a class (no global constants) but you can make a constant public and have access to it using ClassName.ConstantName so long as you have added the class to the project. This works even without creating the class as if the public constants were static, but you cannot use the Shared keyword.

Constants must be of an integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration, or a reference to null.

Public Class Convert
Inherits System.Object
 
  Public Const kName As String = "Mike"
  Private Const kPI Double = 3.1459
 
  //Declare two or more on same line too:
Const kFeetToMeter = 3.2808, kMeterToFeet = 0.3048
End Class
-Collapse +Expand 168. VB.Net Deployment Overview
 

VB.Net projects require the .Net framework and any additional dependencies you've added such as Crystal Reports.

In Visual Studio.Net, you can create a Setup and Deployment project by using any of the templates available on the New Project dialog (Other Project Types).

In addition, VB.Net projects also support ClickOnce which brings the ease of Web deployment to Windows Forms and console applications. To get started, right click on your solution in the Solution Explorer, click Properties then select the Security tab. 

In addition, you can use any of the many free and commercially available installation packages.

-Collapse +Expand 169. VB.Net Development Tools
 

Languages Focus: Development Tools

Primary development tool(s) used to develop and debug code.

VB.Net Development Tools

Microsoft Visual Basic Express Editions (as in Visual Basic 2008 Express Edition) and the full version of Microsoft Visual Studio.Net are the current primary tools. VB.Net is not compatible with VB Classic.

-Collapse +Expand 170. VB.Net End of Statement (Return)
 

Languages Focus: End of Statement

In coding languages, common End of statement specifiers include a semicolon and return (others exist too). Also of concern when studying a language is can you put two statements on a single code line and can you break a single statement into two or more code lines.

VB.Net End of Statement

A return marks the end of a statement and you cannot combine statements on a single line of code. You can break a single statement into two or more code lines by using a space and underscore " _".

Console.WriteLine("Hello1")
Console.WriteLine("Hello2")
Console.WriteLine("Hello3")

'The following commented code
'on a single line does not work...
'Console.WriteLine("Hello4") Console.WriteLine("Hello5")

'Two or more lines works too with a space+underscore:
Console.WriteLine _
"Hello6";
-Collapse +Expand 171. VB.Net Literals (quote)
 

General Info: Programming Literals

A value directly written into the source code of a computer program (as opposed to an identifier like a variable or constant). Literals cannot be changed. Common types of literals include string literals, floating point literals, integer literals, and hexidemal literals. Literal strings are usually either quoted (") or use an apostrophe (') which is often referred to as a single quote. Sometimes quotes are inaccurately referred to as double quotes.

Languages Focus: Literals

In addition to understanding whether to use a quote or apostrophe for string literals, you also want to know how to specify and work with other types of literals including floating point literals. Some compilers allow leading and trailing decimals (.1 + .1), while some require a leading or trailing 0 as in (0.1 + 0.1). Also, because floating point literals are difficult for compilers to represent accurately, you need to understand how the compiler handles them and how to use rounding and trimming commands correctly for the nature of the project your are coding.

VB.Net Literals

String literals are quoted as in "Prestwood". If you need to embed a quote use two quotes in a row.

To specify a floating point literal between 1 and -1, preceed the decimal with a 0. If you don't, the compiler will auto-correct your code and place a leading 0. It will change .1 to 0.1 automatically. Trailing decimals are not allowed.

Console.WriteLine("Hello")
Console.WriteLine("Hello ""Mike"".")
  
'Does VB.Net evaluate this simple
'floating point math correctly? No! 
If (.1 + .1 + .1) = 0.3 Then
MsgBox "Correct"
Else
MsgBox "Not correct"
End If
-Collapse +Expand 172. VB.Net Overview and History
 

Language Overview: VB.Net is an OOP language (no global functions or variables). You code using a fully OOP approach (everything is in a class).

Target Platforms: VB.Net is most suitable for creating any type of application that runs on the .Net platform. This includes desktop business applications using WinForms and websites using WebForms.

-Collapse +Expand 173. VB.Net Report Tools Overview
 

Microsoft includes ReportViewer Starting with Visual Studio 2005. You can even surface this .Net solution in your VB Classic application if you wish. For WebForm applications the client target is the browser (a document interfaced GUI), a common solution is to simply output an HTML formatted page with black text and a white background (not much control but it does work for some situations). For WinForm applications, Crystal Reports is still very popular with VB.Net developers because it has been bundled with Visual Basic since VB 3, it's overall popularity, and compatibility with many different development tools.

-Collapse +Expand 174. VB.Net String Concatenation (+ or &)
 

Most (many?) developers recommend using "+" because that's what C# uses but "&" is also available and many VB Classic and VBA/ASP developers prefer it. My preference is to use the & because it offers implicit type casting.

Dim FullName
Dim Age
  
//You can use + for strings.
FullName = "Prestwood"
Console.WriteLine("Hello " + FullName)
 
//For implicit casting, use &
Age = 35
Console.WriteLine(FullName & " is " & Age & " years old.")
'Implicit casting of numbers.
'
'This works:
MessageBox.Show(3.3)
  
'This fails:
'MessageBox.Show("" + 3.3)
  
'This works:
MessageBox.Show("" + CStr(3.3))
  
'Implicit casting &. This also works:
MessageBox.Show("" & 3.3)
-Collapse +Expand 175. VB.Net Variables (Dim x As Integer=0)
 

Variables are case sensitive but VS.Net will auto-fix your variable names to the defined case. You can declare variables in-line wherever you need them and declarative variable assignment is supported.

Dim FullName As String

Dim Age As Integer

Dim Weight As Double

FullName = "Mike Prestwood"

Age = 32

Weight = 154.4

'Declaritive variable assignment:

Dim Married As String = "Y"

MsgBox(Married)




Topic: Language Basics

-Collapse +Expand 176. VB.Net Associative Array (Dictionary)
 

An associative array links a set of keys to a set of values. In Visual Basic, associative arrays are implemented as Dictionaries.

This code produces a message box saying "Nevada."

//Imports System.Collections.Generic
Dim States As New Dictionary(Of String, String)

States.Add("CA", "California")
States.Add("NV", "Nevada")
 
MsgBox(States("NV"))
-Collapse +Expand 177. VB.Net Comparison Operators (=, <>)
 

Same as VB Classic.

//Does VB.Net evaluate the math correctly? No!
If 0.1 + 0.1 + 0.1 = 0.3 Then
MessageBox.Show("correct")
Else
MessageBox.Show("not correct")
End If
-Collapse +Expand 178. VB.Net Custom Routines (Sub, Function)
 

VB.Net is a fully OOP language so both Subs and Functions are methods of a class. A Sub does not return a value while a Function does.

Private Sub DoSomething(ByVal pMsg As String)
'...some code.
End Sub

Private Function GetAge(ByVal x As String) As Integer
GetAge = 7
End Function
-Collapse +Expand 179. VB.Net Exception Trapping (Try...Catch...Finally)
 

A common usage of exception handling is to obtain and use resources in a "try-it" block, deal with any exceptions in an "exceptions" block, and release the resources in some kind of "final" block which executes whether or not any exceptions are trapped.

Try
Dim y As Integer = 0
y = 1 / y
Catch
MessageBox.Show("you cannot divide by zero")

End Try
-Collapse +Expand 180. VB.Net Logical Operators
 

VB.Net logical operators:

And and, as in this and that
Or or, as in this or that
Not Not, as in Not This
Xor either or, as in this or that but not both

'Given expressions a, b, c, and d:
If Not (a and b) and (c or d) Then
  'Do something.
End If
-Collapse +Expand 181. VB.Net Overloading (Overloads, or implicit)
 

VB.Net supports both method and operator overloading.

For method overloading, you either use implicit overloading (no special syntax like C#) or use the Overloads keyword. If you use the Overloads keyword, all overloaded methods with the same name in the same class must include the Overloads keyword.

-Collapse +Expand 182. VB.Net Unary Operators
 

An operation with only one operand (a single input). The following are the�VB.Net unary operators: +, -, isFalse, isTrue, and Not. A unary operator method can return any type but takes only one parameter, which must be the type of the containing class.




Topic: Language Details

-Collapse +Expand 183. VB.Net Inlining (Automatic)
 

In VB.Net, inlining is automatically done for you by the JIT compiler for all languages and in general leads to faster code for all programmers whether they are aware of inlining or not.

-Collapse +Expand 184. VB.Net Pointers (None)
 

VB.Net doesn't support pointers. The closest it comes is IntPtr which you use to get pointer handles on windows, files, etc.

C# does have better support for pointers and C++/CLI has extensive support. One solution when it's really needed in VB.Net is to code in C# or C++/CLI and add it to your project.

However, VB.Net does support references.




Topic: OOP

-Collapse +Expand 185. VB.Net Abstraction (MustInherit, MustOverride, Overrides)
 

VB.Net supports abstract class members and abstract classes using the MustInherit and MustOverride modifiers.An abstract class is indicated with a MustInherit modifier and is a class with one or more abstract members and you cannot instantiate an abstract class. However, you can have additional implemented methods and properties. An abstract member is either a method (implicitly virtual), property, indexer, or event in an abstract class. You can add abstract members ONLY to abstract classes using the MustOverride keyword. Then you override it in a descendant class with Overrides.

Public MustInherit Class Cyborg
  Public MustOverride Sub Speak(ByVal pMessage As String)
End Class

Public Class Series600
  Inherits Cyborg

  Public Overrides Sub Speak(ByVal pMessage As String)
    MessageBox.Show(pMessage)
  End Sub
End Class
-Collapse +Expand 186. VB.Net Access Modifiers
 

In VB.Net, you specify each class and each class member's visibility with an access modifier preceding class or member. The VB.Net access modifiers are the traditional Public, Protected, and Private plus the two additional .Net modifiers Friend and Protected Friend.

Friend indicates members are accessible from types in the same assembly. Protected Friend indicates members are accessible from types in the same assembly as well as descendant classes. OO purist might object to Friend and Protected Friend and I suggest you avoid them until you both fully understand them and have a need that is best suited by them.

Public Class Cyborg
Inherits Object
 
  Private FName As String
End Class
-Collapse +Expand 187. VB.Net Base Class (System.Object)
 

In VB.Net, the Object keyword is an alias for the base System.Object class and is the single base class all classes ultimately inherit from.

'Specify both namespace and class:
Public Class Cyborg
Inherits System.Object
End Class
  
'Use Object alias for System.Objct:
Public Class Cyborg
Inherits Object
End Class
  
'Default when not specified is System.Object:
Public Class Cyborg
End Class
-Collapse +Expand 188. VB.Net Class..Object (Class..End Class..New)
 

Declare and implement VB.Net classes after the form class or in their own .vb files. Unlike VB Classic, you can have more than one class in a .vb class file (VB classic uses .cls files for each class).

Class definition:

Public Class Cyborg
  Inherits Object
 
  Public Sub IntroduceYourself()
  MessageBox.Show("Hi, I do not have a name yet.")
 End Sub
End Class

Some event like a button click:

Dim T1 As New Cyborg
T1.IntroduceYourself()
//No need to clean up with managed classes.
//The garbage collector will take care of it.
-Collapse +Expand 189. VB.Net Constructors (New)
 

 A sub named New. You can overload the constructor simply by adding two or more New subs with various parameters.

Public Class Cyborg
Public CyborgName As String
  
  Public Sub New(ByVal pName As String)
CyborgName = pName
End Sub
End Class
Public Class Cyborg
Public CyborgName As String
  
  Public Sub New(ByVal pName As String)
CyborgName = pName
End Sub
End Class
-Collapse +Expand 190. VB.Net Finalizer (Finalize())
 

Use a destructor to free unmanaged resources. A destructor is a method with the same name as the class but preceded with a tilde (as in ~ClassName). The destructor implicity creates an Object.Finalize method (you cannot directly call nor override the Object.Finalize method).

In VB.Net you cannot explicitly destroy an object. Instead, the .Net Frameworks garbage collector (GC) takes care of destroying all objects. The GC destroys the objects only when necessary. Some situations of necessity are when memory is exhausted or you explicitly call the System.GC.Collect method. In general, you never need to call  System.GC.Collect.

Class Cyborg
� Protected Overrides Sub Finalize()
��� 'Free non-managed resources here.
��� MyBase.Finalize()
� End Sub
End Class
-Collapse +Expand 191. VB.Net Inheritance (Inherits ParentClass)
 

VB.Net uses the Inherits keyword followed by the parent class name. If you do not include Inherits, your class inherits from System.Object.

In the following example, a terminator T-600 is-an android. 

Public Class Android
End Class
 
Public Class T-600
  Inherits Android
End Class
-Collapse +Expand 192. VB.Net Inheritance-Multiple (Not Supported)
 

VB.Net does not support multiple implementation inheritance. Each class can have only one parent class (a single inheritance path). In VB.Net, you can use multiple interface usage to design in a multiple class way horizontally in a class hierarchy.

-Collapse +Expand 193. VB.Net Interfaces (Interface, Implements)
 

With VB.Net you define an interface with the Interface keyword and use it in a class with the Implements keyword. In the resulting class, you implement each property and method and add Implements Interface.Object to each as in:

Sub Speak(ByVal pSentence As String) Implements IHuman.Speak
  MessageBox.Show(pSentence)
End Sub
Public Interface IHuman
'Specify interface methods and properties here.
End Interface

Public Class Cyborg
Inherits System.Object
End Class

Public Class CyborgHuman
Inherits Cyborg
Implements IHuman
'Implement interface methods and properties here.
End Class
-Collapse +Expand 194. VB.Net Member Field
 

In VB.Net you can set the visibility of a member field to any visibility: private, protected, public, friend or protected friend.

You can intialize a member field with a default when declared. If you set the member field value in your constructor, it will override the default value.

Finally, you can use the Shared modifier (no instance required) and ReadOnly modifier (similar to a constant).

Public Class Cyborg
  Private FSerialNumber As String = "A100"
 
  Public CyborgName As String
  Public CyborgAge As Integer
  Public Shared ReadOnly SeriesID As Integer = 100
End Class
-Collapse +Expand 195. VB.Net Member Method (Sub, Function)
 

VB.Net uses the keywords sub and function. A sub does not return a value and a function does. Many programmers like to use the optional call keyword when calling a sub to indicate the call is to a procedure.

Class definition:

Public Class Cyborg
� Inherits Object
 
Public Sub IntroduceYourself()
��� MessageBox.Show("Hi, I do not have a name yet.")
� End Sub
End Class

Some event like a button click:

Dim T1 As New Cyborg
T1.IntroduceYourself()
-Collapse +Expand 196. VB.Net Member Modifiers
 

The method modifiers include MustOverride, NotOverridable, Overridable, Overrides. Specify VB.Net member modifiers as follows:

Public Overrides Function SomeFunction() As Double

The field modifiers include ReadOnly and Shared. Specify field modifiers as follows:

Public ReadOnly SomeField As String

-Collapse +Expand 197. VB.Net Member Property (property, get, set)
 

VB.Net uses a special property keyword along with special get and set methods to both get and set the values of properties. For a read-only property, leave out the set method. The value keyword is used to refer to the member field. Properties can make use of any of the access modifiers (private, protected, etc).

My preference for VB.Net code is to start member fields with "F" ("FName" in our example) and drop the "F" with properties that manage member fields ("Name" in our example).

Public Class Cyborg
Private FCyborgName As String
 
  Public Property CyborgName()
Get
Return F
CyborgName
End Get
 
Set(ByVal value)
F
CyborgName = value
End Set
End Property
End Class
-Collapse +Expand 198. VB.Net Overriding (Overridable, Overrides)
 

In VB.Net, you specify a virtual method with the Overridable keyword in a parent class and extend (or replace) it in a descendant class using the Overrides keyword.

Use the base keyword in the descendant method to execute the code in the parent method, i.e. base.SomeMethod().

Public Class Robot
Public Overridable Sub Speak()
MessageBox.Show("Robot says hi")
End Sub
End Class
  
Public Class Cyborg
Inherits Robot
  
  Public Overrides Sub Speak()
MessageBox.Show("hi")
End Sub
End Class
-Collapse +Expand 199. VB.Net Partial Classes (Partial)
 

VB.Net supports both partial classes and partial methods.

Partial Public Class Cyborg
Inherits System.Object
End Class
-Collapse +Expand 200. VB.Net Polymorphism
 
-Collapse +Expand 201. VB.Net Prevent Derivation (NotInheritable, NotOverridable)
 

With VB.Net, use the NotInheritable keyword to prevent a class from being inherited from and use the NotOverridable keyword to prevent a method from being overridden.

A method marked NotOverridable must override an ancestor method. If you mark a class NotInheritable, all members are implicitly not overridable so the NotOverridable keyword is not legal.

Public Class Machine
  Public Overridable Sub Speak(ByRef pSentence As String)
MessageBox.Show(pSentence)
End Sub
End Class
  
Public Class Robot
Inherits Machine
  Public NotOverridable Overrides Sub Speak(ByRef pSentence As String)
MessageBox.Show(pSentence)
End Sub
End Class
  
Public NotInheritable Class Cyborg
Inherits Robot
End Class
-Collapse +Expand 202. VB.Net Self Keyword (Me)
 

To refer to the current instance of a class or structure, use the Me keyword. Me provides a way to refer to the specific instance in which the code is currently executing. It is particularly useful for passing information about the currently executing instance.

The Me keyword is also used as a modifier of the first parameter of an extension method.

You cannot use Me with static method functions because static methods do not belong to an object instance. If you try, you'll get an error.

Sub SetBackgroundColor(FormName As Form)
  //FormName.BackColor = ...some color
End Sub
  
//Pass Me.
SetBackgroundColor(Me)
-Collapse +Expand 203. VB.Net Shared Members (Shared)
 

VB.Net supports both static members and static classes (use the keyword Shared). You can add a static method, field, property, or event to an existing class.

You can designate a class as static and the compiler will ensure all methods in that class are static. You can add a constructor to a static class to initialize values.

The CLR automatically loads static classes with the program or namespace.

Public Shared Function MySharedFunction() As Integer
  MySharedFunction = 12345
End Function



Group: Corel Paradox / ObjectPAL Coding





Topic: Paradox & ObjectPAL

-Collapse +Expand 204. ObjectPAL Array (Array[] type)
 

Arrays in ObjectPAL use a 1-based indice.

Use size() to get the number of elements. size() returns 0 if the array has no elements.

var
  MyArray Array[4] String ;Fixed size array.
  i LongInt
endVar

MyArray[1] = "Mike"
MyArray[2] = "Lisa"
MyArray[3] = "Felicia"
MyArray[4] = "Nathan"

if MyArray.size() > 0 then
  for i from 1 to MyArray.size()
    msgInfo("", MyArray[i])
  endFor
endIf




Topic: Installation, Setup, & BDE

-Collapse +Expand 205. ObjectPAL File Extensions
 

Paradox for Windows has two primary file types: source files and delivered files. Source files in Paradox are binary but can can be opened in later versions of Paradox and even in earlier versions if you don't use any new features: .FSL = Form, .RSL = Report, .SSL = Script, and .LSL = Library. Since Paradox source files do not compile to an EXE, Paradox developers tend to use a startup form or script to start the application.




Topic: OPAL: Language Basics

-Collapse +Expand 206. ObjectPAL Assignment (=)
 

ObjectPAL uses = for it's assignment operator.

var
 FullName String
   Age SmallInt
endVar
  
FullName = "Randy Spitz"
Age = 42
-Collapse +Expand 207. ObjectPAL Case Sensitivity (No)
 

ObjectPAL is not case sensitive. My preference for ObjectPAL is to follow the camel casing promoted in the examples and help files originally developed by Borland.

All of the following are equivalent:

msgInfo "", "Hello"
MsgInfo "", "Hello"
msginfo "", "Hello"
MSGINFO "", "Hello"

Variables are not case sensitive.

Var
FullName String
endVar
fullname="Mike Prestwood"
msgInfo("", fullNAME)
-Collapse +Expand 208. ObjectPAL Code Blocks (endXxxx)
 

ObjectPAL code blocks are surrounded by statement ending keywords that all use End with camel caps such as endMethod, endVar, endIf, endSwitch, and endTry.

method
endMethod
 
var
endVar
 
if
endIf
 
switch
endSwitch
 
try
endTry
-Collapse +Expand 209. ObjectPAL Comments (; and { ... })
 

Commenting Code
ObjectPAL uses ; for a single line comment and { } for a multiple line comment.

;Single line comment.

{
Multiple line
comment.
}
-Collapse +Expand 210. ObjectPAL Comparison Operators (=, <>)
 

Common comparison operators:

= equal
<> not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

'Does ObjectPAL evaluate the math correctly? No!
If .1 + .1 + .1 = .3 Then
msgInfo("", "correct")
Else
msgInfo("", "not correct")
endIf
-Collapse +Expand 211. ObjectPAL Constants (const..endConst)
 

In ObjectPAL, you declare one or more constant values within a const..endConst block. Optionally, you can specify the dataType by casting the value as part of the declaration. If you do not specify the data type, the data type is inferred from the value as either a LongInt, a Number, a SmallInt, or a String. As with variables, the const..endConst block can come within a method or procedure as the first bit of code, or in the Const window. Putting it above the method or procedure is allowed but has no significance so don't.

const
kFeetToMeter = Number(3.2808)
kMeterToFeet = Number(.3048)
kName = String("Mike")
  kCA = "California"     ;String inferred.
endConst
-Collapse +Expand 212. ObjectPAL Development Tools
 

Corel Paradox for Windows (was Borland Paradox). Also, Borland used to offer a Paradox for DOS tool which support it's Paradox Application Language (PAL) which is not compatible with ObjectPAL. The biggest drawback to Paradox is that Corel does not have anyone at Corel actively developing Paradox for Windows (as opposed to Microsoft Access which does).

-Collapse +Expand 213. ObjectPAL Edit Record (insertRecord, postRecord, edit)
 

In ObjectPAL, you use Cursor.InsertRecord to add a new record, Cursor.postRecord to post the record, and Cursor.deleteRecord() to delete it. To edit a record, you must put the cursor into edit mode, Cursor.Edit(). (A cursor applies to both a TCursor and UIObject.)

ObjectPAL gives you tremendous flexibility with editing data and includes many additional commands such as insertAfterRecord and isEdit. For dBASE tables, you can also use unDeleteRecord() to un-delete a record. See the ObjectPAL help for more commands.

The following code snippet adds a record to a given TCursor with FullName and Created fields:

tc.edit()
tc.InsertRecord()
tc.FullName = "Barack Obama"
tc.Created  = today()
tc.postRecord
-Collapse +Expand 214. ObjectPAL Empty String Check (isBlank() or not isAssigned())
 

In ObjectPAL, an empty variable can be unassigned (essentially null) or blank (equivalent to ""). You have to use both isBlank and isAssigned to check for an empty string.

var
 s String
endVar
  
;s = ""  ;Uncomment to test 2nd case.
 
if isBlank(s) or not isAssigned(s) Then
 msgInfo("", "empty string")
endIf
-Collapse +Expand 215. ObjectPAL End of Statement (whitespace)
 

Languages Focus: End of Statement

In coding languages, common End of statement specifiers include a semicolon and return (others exist too). Also of concern when studying a language is can you put two statements on a single code line and can you break a single statement into two or more code lines.

ObjectPAL End of Statement

ObjectPAL is a bit unique in that it doesn't use a semicolon nor a return to mark the end of a line, it uses whitespace which can be a return, space, or tab. This is a bit unusual but does allow for some nice formatting of code.

msgInfo("", "Hello1")
msgInfo("", "Hello2")
msgInfo("", "Hello3")

;The following single line of code also works.
msgInfo("", "Hello4") msgInfo("", "Hello5")

;Two or more works too:
msgInfo
("", "Hello6")
-Collapse +Expand 216. ObjectPAL If Statement (If..Else..EndIf, or switch)
 

ObjectPAL supports a simple If...Else...EndIf statement.

Notice ObjectPAL does not support an ElseIf feature as part of an if statement. Instead use a switch statement

'Does ObjectPAL evaluate the math correctly? No!
If (.1 + .1 + .1) = .3 Then
  msgInfo("", "Correct")
Else
  msgInfo("", "Not correct")
EndIf
 
'Switch statement example.
switch
case x = "Nate": MsgInfo("", "Hi Nate")
case x = "Felicia": MsgInfo("", "Hi Felly")
  otherwise: MsgInfo("", "Who are you?")
endSwitch
-Collapse +Expand 217. ObjectPAL Literals (quote)
 

Literals are quoted as in "Prestwood".  If you need to embed a quote use a slash in front of the quote as in \"

In ObjectPAL, string literals are limited to 255 characters but there's nothing preventing you from using multiple string literals together as in:

msgInfo("", "Hi Mike: " + "You can add literals together in ObjectPAL")
msgInfo("", "Hello")
msgInfo("", "Hello \"Mike\".")
  
;Does ObjectPAL evaluate this simple
;floating point math correctly? No!
If (.1 + .1 + .1) = .3 Then
 msgInfo("", "Correct")
Else
 msgInfo("", "Not correct")
EndIf
-Collapse +Expand 218. ObjectPAL Logical Operators
 

ObjectPAL logical operators:

and and, as in this and that
or or, as in this or that
Not Not, as in Not This

;Given expressions a, b, c, and d:
if Not (a and b) and (c or d) then
  ;Do something.
endIf
-Collapse +Expand 219. ObjectPAL String Concatenation (+)
 

String literals s are limited to 255 characters but you can simply add two strings together as in:

s = "A long string." + "Another long string."
var
FirstName  String
  LastName  String
endVar
 
FirstName  = "Mike"
LastName  = "Prestwood"
msgInfo("", "Full name: " + FirstName + " " + LastName)
-Collapse +Expand 220. ObjectPAL Unary Operators
 

The ObjectPAL unary operators are:

+
-
Not

-Collapse +Expand 221. ObjectPAL Variables (var x SmallInt endVar)
 

Declaring variables is optional unless you click Program | Compiler Warnings while in the ObjectPAL editor for every form, script, and library you create. Using Compiler Warnings is strongly recommended to avoid incorrectly typing an existing variable and to avoid any confusion about variable scope. Also recommended is turning on Compile with Debug for every form, script, and library too for tighter, cleaner code.

Undeclared variables are AnyType variables. Common data types include Currency, Date, Datetime, Logical, LongInt, Number, SmallInt, String, and Time.

Declare local variables within a method. If you want a local static variable (retains it's value because it is not destroyed), declare the varialbes above the method. Variables declared in an object's Var window are visible to all methods attached to that object, and objects that it contains.

var
    FullName String
    Age SmallInt
    Weight Number
endVar
 
FullName = "Mike Prestwood"
Age = 32
Weight =154.4
msgInfo("", FullName + ", age=" + String(Age) 
             + ", weight=" + String(Weight))



Topic: OPAL: Language Details

-Collapse +Expand 222. Assocative Arrays in ObjectPAL
 

An associative array links a set of unique values (keys) to another set of values (not necessarily unique). In ObjectPAL associative arrays are known as dynamic arrays.

;Button :: pushButton
method pushButton(var eventInfo Event)
var
myDynArray   DynArray[] String
endVar

 
myDynArray["Last_Name"] = "Spitz"
myDynArray["First_Name"] = "Randy"
myDynArray.view()
endMethod
-Collapse +Expand 223. ObjectPAL Associative Array (DynArray)
 

In ObjectPAL associative arrays are known as dynamic arrays.

var
myDynArray   DynArray[] String
endVar

 
myDynArray["Last_Name"] = "Spitz"
myDynArray["First_Name"] = "Randy"
myDynArray.view()
-Collapse +Expand 224. ObjectPAL Exception Trapping (try...onFail)
 

ObjectPAL has a try...onFail statement but does not have a finally-type component. However, the code afer endTry will execute.

try
onFail
endTry
var
i SmallInt
endVar
try
i = 0
i = 1/i
onFail
msgInfo("", "You cannot divide by zero.")
endTry
-Collapse +Expand 225. ObjectPAL Filter Records (setRanger, setGenFilter)
 

In ObjectPAL, you can filter set a TCursor, UIObject, and Table objects using setRange() and setGenFilter().

The following example loads, filters, and runs a report.

var
 r Report
 dyn DynArray[] String
endVar
  
dyn["Name"] = "SCUBA Heaven"
Customer.setGenFilter(dyn)
  
r.load(":Sample:customer")
r.Customer.setGenFilter(dyn)
r.run()

You can also drop a flter with:

r.Customer.dropGenFilter()
-Collapse +Expand 226. ObjectPAL Find Record (locate, qLocate)
 

ObjectPAL provides a rich set of commands for finding a record with a TCursor or UIObject including:

  • locate() -  Seach for a value based on a criteria. Uses indexes as appropriate.
  • locatePattern() - Search for a pattern within a value.
  • moveToRecord() - Moves to a specific record number.
  • qLocate() - Search using currently set index.

Each of these basic find record commands has supporting commands such as locateNext() and recNo().

var
  tc TCursor
endVar
   
tc.open("Customer.db") 
if tc.locate("Name", "Proffessional Divers, Ltd.") then 
  tc.edit()
  tc.Name = "Professional Divers, Ltd."
  msgInfo("Success", "Corrected spelling error.")
endIf
tc.endEdit()
-Collapse +Expand 227. ObjectPAL Overloading
 

Paradox & Overloading

  • Operator - No.
  • Method - No.

However, you can have the same named method or procedure so long as they are in different libraries. This is important if you use libraries in a class-like OOP way and wish to implement some form of polymorphism (i.e. libMember.Open and libVendor.Open). This is an OOP-like technique for implementing a subtyping-like polymorphism which is also known as inclusion polymorphism.

Also, some developers like to pass an array and then handle the array for a pseudo technique. Although not overloading, it's useful.

-Collapse +Expand 228. ObjectPAL Parameters (var, const)
 

By Reference or Value (and by constant)
The default for parameters is by value. For by reference, add var in front of the parameter. ObjectPAL also offers constant parameters where you add const in front of the parameter. A constant parameter is like a read-only parameter the compiler can optimize. You cannot assign a value to a constant parameter.

method cmCode(s String) ;...s is by value.
endMethod
 
  
method pushButton(var eventInfo Event)
  ;...eventInfo is by reference.
endMethod
  
method cmCode(Const s String)
  ;...s is a constant read-only parameter.
endMethod
  
proc cpNever() String
  return "Never duplicate a line of code!"
endProc

-Collapse +Expand 229. ObjectPAL Record Movement (home, end, nextRecord)
 

ObjectPAL uses home(), end(), nextRecord(), priorRecord() to move a database cursor (works with either a TCursor or UIObject).

TCursor.nextRecord()

These commands send a message to the object. Specifically, they send an action constant using the action command. The above snippet is equivalent to:

TCursor.action(DataNextRecord)

It is handy to  with familiar with action constants because not all action constants have an ObjectPAL equivalent comment.

The following snippet uses the active keyword to move to the second to last record of the table attached to the UIObject that currently has focus:

active.end()
active.priorRecord()

You can also use the self keyword to refer to the UIObject your code is attached to.

-Collapse +Expand 230. ObjectPAL Self Keyword (Self)
 

A built-in object variable that represents the UIObject to which the currently executing code is attached.

method pushButton(var eventInfo Event)
  msgInfo("", self.Name)
endMethod
-Collapse +Expand 231. ObjectPAL Sort Records (switchIndex, sortTo, setGenFilter)
 

In Paradox, you add an index for each sort your wish to perform on a table then use switchIndex(). Alternatively, you can use sortTo() to sort a table into a new table.

-Collapse +Expand 232. ObjectPAL subStr
 

substr ( const startIndex LongInt [ , const numberOfChars LongInt ] ) String

Alternative syntax:

LeftString = subStr(NameVar, 1, 3)
var
�LeftString String;
  NameVar String;
endVar
NameVar = "Prestwood"
LeftString = NameVar.subStr(1, 3)
msgInfo("", LeftString)



Topic: Interactive Paradox: Queries (QBE)

-Collapse +Expand 233. @ and ..
 
The first half is an inexact search and the second half tells it to limit the search to four characters.

QBE Expression...

 

mIkE.., @@@@



Topic: Interactive Paradox: Reports

-Collapse +Expand 234. ObjectPAL Report Tools Overview (Built-In)
 

Paradox offers a built-in reporting tool that will suffice for most desktop database applications.




Topic: ObjectPAL Coding

-Collapse +Expand 235. ObjectPAL Overview and History
 

Language Overview: Object based language. Although ObjectPAL uses object oriented techniques "under the hood", it is not object oriented. Although you cannot create classes, ObjectPAL has built-in objects you can use in your code. You code in a traditional approach attaching code to objects or within a script. Most Paradox applications are form based. You may have a short startup script but you design forms and reports and tie them together with a common form. You can store reusable code such as custom methods and procedures in a library.

Target Platforms: Corel Paradox is most suitable for creating business desktop applications that run within Corel Paradox for Windows.




Topic: OPAL: Commands

-Collapse +Expand 236. ObjectPAL setTitle()
 

This code sets the title of your Paradox application in the application's title bar.

var
	app Application
endVar
app.setTitle("My Custom Application")



Topic: OPAL: Libraries

-Collapse +Expand 237. ObjectPAL Custom Routines (method, procedure)
 

ObjectPAL is a non-OOP language (an object-based language) that offers custom methods and custom procedures. When you create a custom method, you associate it with an existing object like a button, form, or library.

When calling a custom method or procedure that has a by reference parameter (uses var), then you cannot use a literal value. this is different than in many other languages which do allow you to pass literals by reference.

method sayHello(var pName String)
 msgInfo("", "Hello " + pName)
endMethod

method add(p1 Number, p2 Number) Number
 Return p1 + p2
endMethod
-Collapse +Expand 238. ObjectPAL Pointers
 

ObjectPAL doesn't use pointers except for use with DLLs where you use a special CPTR uses keyword to refer to a DLL string pointer data type.

Uses Tapi32
  tapiRequestMakeCall(sNumber CPTR, sAppName CPTR, 
    sLogName CPTR, sComment CPTR) CLONG
endUses



Topic: OPAL: OOP

-Collapse +Expand 239. ObjectPAL Inheritance (Not Supported)
 

ObjectPAL does not support developer defined class creation nor sub-classing (inheritance).

-Collapse +Expand 240. ObjectPAL Polymorphism (Not Supported)
 

Built-in: In ObjectPAL, polymorphism is the capability of the built-in objects to act differently depending on the context in which they are being used. For example, Table.Open and TCursor.Open. The Open method works differently depending on the object type used.

Custom: No. However,you can have the same named method or procedure so long as they are in different libraries.This is importantif you use librariesin a class-like OOP way and wish to implement some form of interfaces-like polymorphism(i.e. libMember.GetName and libVendor.GetName).




Topic: OPAL: Wicked Coding Tasks

-Collapse +Expand 241. Calling an Oracle Stored procedure from Paradox
 

In Paradox, use an sqlQuery block to call store procedures. The following code uses an sqlQuery block to call an Oracle stored procedure. Use the syntax of whatever SQL server you're going against. With Oracle, if I remember correctly, you use an "execProc" or "exec" command.

sqlQuery =
SQL
;execute proc here
ENDSQL


if not dbSQL.executeSQL(sqlQuery, tcAnswer) then
errorShow()
endIf
-Collapse +Expand 242. OLEAuto Paradox to Outlook
 

The following code snippet adds an appointment to your Outlook calendar. Tested with Paradox 9 and Outlook 2003 but should work with later versions of both programs.

Note, you will get a Error opening server 'Outlook.Application' error if your antivirus program is blocking Outlook access.

var
 oleOutlook oleAuto
 oleAppointment oleAuto
endVar
  
;The open will fail if your AntiVirus program is blocking access.
oleOutlook.open("Outlook.Application")
oleAppointment=oleOutlook.CreateItem(1)
  
oleAppointment.Subject = "Test From ObjectPAL"
oleAppointment.Body="You can add appointments from ObjectPAL."
oleAppointment.Start=dateTime() ;Adds an appointment now.
oleAppointment.Duration=60
oleAppointment.ReminderSet=True
oleAppointment.Location="My Office"
oleAppointment.BusyStatus = 2
  
oleAppointment.save()



Topic: Runtime, PDE, Package-It!

-Collapse +Expand 243. ObjectPAL Deployment Overview
 

To deploy a Paradox application, you need to deploy either the full version of Paradox or the Paradox Runtime both of which will include the BDE as well as any dependecies you've added such as psSendMail DLL, ezDialogs, etc.




Group: Visual Basic Classic





Topic: VB Classic

-Collapse +Expand 244. VB Classic Array (x = Array())
 

Arrays in VB Classic use a 0-based indice. UBound returns -1 if the array has no elements, 0 if it has 1, 1 if it has 2, etc.

Dim MyArray As Variant
Dim i As Integer
 
MyArray = Array("Mike", "Lisa", "Felicia", "Nathan")
 
If UBound(MyArray) > -1 Then
  For i = 0 To UBound(MyArray)
    MsgBox (MyArray(i))
  Next
End If
-Collapse +Expand 245. VB Classic Empty String Check (Len(s&vbNullString))
 

In VB Classic, you have to add an empty string to the value being compared in order to get consistent results. For example, add &"" to your string varilable or it's code equivalent &vbNullString. Then compare to an empty string or verify it's length to 0 with Len.

All these will work for variables unassigned, set to "", or set to Null:

If s&"" = "" Then
MsgBox ("Quotes with &'' say null is empty")
End If
 
If Len(s&"") = 0 Then
MsgBox ("Len with &'' says null is empty")
End If
 
If Len(s&vbNullString) = 0 Then
MsgBox ("Using vbNullString also works!")
End If
-Collapse +Expand 246. VB Classic File Extensions
 
  • .BAS = VB source code file.
  • .CLS = VB class file (one class per file).
-Collapse +Expand 247. VB Classic Parameters (ByRef, ByVal)
 

By Reference or Value
For parameters, you can optionally specify ByVal or ByRef. ByRef is the default if you don't specify.

Function SomeRoutine(ByRef pPerson, ByVal pName, Age)



Topic: Tool Basics

-Collapse +Expand 248. VB Classic Assignment (=)
 

VB Classic uses = for it's assignment operator.

Dim Age As Integer
Dim FullName As String
   
FullName = "Randy Spitz"
Age = 38
-Collapse +Expand 249. VB Classic Case Sensitivity (No)
 

VB Classic is not case sensitive. If you type any other case for commands or variables, VB Classicwill change it to the "accepted" or "defined" case. For example, if you type msgbox it is converted to MsgBox.

The following code works:

MsgBox ("hello")
-Collapse +Expand 250. VB Classic Code Blocks (End Xxx)
 

VB Classiccode blocks are surrounded by statement ending keywords that all use End such as End Sub, End If, and WEnd.

Sub x
End Sub
 
If x Then
End If
  
While x
WEnd
-Collapse +Expand 251. VB Classic Comments (' or REM)
 

Commenting Code
VB Classic, like all the VB-based languages, uses a single quote (') or the original class-style basic "REM" (most developers just use a quote). VB Classic does NOT have a multiple line comment.

Directives - #

Directives are sometimes called compiler or preprocessor directives. A # is used for directives within VB Classic code. VB Classic offers only an #If..then/#ElseIf/#Else directive.

'Single line comment.

REM Old school single line comment.

#If MyDirective Then
'...some code.
#End If

 

-Collapse +Expand 252. VB Classic Comparison Operators (=, <>)
 

Save as VB Classic. Common comparison operators:

= equal
<> not equal
< less than
> greater than
<= less than or equal
>= greater than or equal
//Does VB evaluate the math correctly? No!
If 0.1 + 0.1 + 0.1 = 0.3 Then
MsgBox "correct"
Else
MsgBox "not correct"
End If
-Collapse +Expand 253. VB Classic Constants (Const kPI = 3.1459)
 

Scope can be Public, Global, or Private. The use of the newer Public keyword is preferred to the older Global. Private Const is the same as just specifying Const.

Const kPI = 3.1459
Const kName = "Mike"
 
//Public variable:
Public Const kFeetToMeter=3.28, kMeterToFeet=.3
-Collapse +Expand 254. VB Classic Deployment Overview
 

VB applications require the VB runtime DLL (for version 6, it's VB600.DLL) plus any additional dependencies you've added such as Crystal Reports, ActiveX controls, and DLLs.

You can use any of the many free and commercially available installation packages.

-Collapse +Expand 255. VB Classic Development Tools
 

Languages Focus: Development Tools

Primary development tool(s) used to develop and debug code.

VB Classic Development Tools

Microsoft Visual Basic 1...6. VB Classic is not compatible with VB.Net.

-Collapse +Expand 256. VB Classic End of Statement (Return)
 

Languages Focus: End of Statement

In coding languages, common End of statement specifiers include a semicolon and return (others exist too). Also of concern when studying a language is can you put two statements on a single code line and can you break a single statement into two or more code lines.

VB Classic End of Statement

A return marks the end of a statement and you cannot combine statements on a single line of code. You can break a single statement into two or more code lines by using a space and underscore " _".

MsgBox "Hello1"
MsgBox "Hello2"
MsgBox "Hello3"

'The following commented code
'on a single line does not work...
'MsgBox "Hello4" MsgBox "Hello5"

'Two or more lines works too with a space+underscore:
MsgBox _
"Hello6";
-Collapse +Expand 257. VB Classic If Statement (If..ElseIf..Else..End If)
 

The End If is optional if you put your code on a single line.

//Single line example.
If X = True Then MsgBox "hello" 
 
//Complete example.
If X = True Then
MsgBox "hello"
ElseIf Y = "ABC" Then
MsgBox "goodbye"
Else
MsgBox "what?"
End If
-Collapse +Expand 258. VB Classic Literals (quote)
 

Literals are quoted as in "Prestwood". If you need to embed a quote use two quotes in a row.

MsgBox ("Hello")
MsgBox ("Hello ""Mike"".")
  
'Does VB evaluate this simple
'floating point math correctly? No! 
If (.1 + .1 + .1) = 0.3 Then
MsgBox "Correct"
Else
MsgBox "Not correct"
End If
-Collapse +Expand 259. VB Classic Overview and History
 

Language Overview: Class based language. Although you can create classes, VB Classic is not fully OOP. It is a traditional language with a few OOP extensions. You code in a traditional approach using functions, procedures, and global data, and you can make use of simple classes to help organize your reusable code. It also supports one-level abstract class to implemented class using the Implements keyword.

Target Platforms: Microsoft Visual Basic 6 is most suitable for creating Windows desktop applications that use the VB600.DLL runtime DLL within Microsoft Windows.

-Collapse +Expand 260. VB Classic Report Tools Overview
 

Crystal Reports was very popular with VB Classic developers and came bundled with Visual Basic 3 through 6. VB6 offers both Crystal Reports and the new Microsoft Data Report Designer.

-Collapse +Expand 261. VB Classic String Concatenation (& or +)
 

Although you can use either a & or a + to concatenate values, my preference is to use a + because more languages use it. However, if you use & then some type conversions are done for you. If you use + you will sometimes have to cast a value to concatenate it. For example, you will have to use CStr to cast a number to a string if you use the + operator as a concatenation operator.

Dim FirstName As String
Dim LastName As String
 
FirstName = "Mike"
LastName = "Prestwood"
 
MsgBox "Full name: " & FirstName & " " + LastName
 
MsgBox "2+2=" + CStr(2+2)
-Collapse +Expand 262. VB Classic Unary Operators
 

An operation with only one operand (a single input) such as + and -.

-Collapse +Expand 263. VB Classic Variables (Dim x As Integer)
 

VB Classic is a loosely typed language. Declaring variables is optional unless you use the Option Explicit statement to force explicit declaration of all variables with Dim, Private, Public, or ReDim. Using Option Explicit is strongly recommended to avoid incorrectly typing an existing variable and to avoid any confusion about variable scope.

Undeclared variables are variants. To specifically declare a variant, use:

Dim x As Variant
Dim x 

Common data types include Byte (0..255), Boolean, Integer (2-byte integers), Long (4-byte integers), Currency, Single (32-bit number), Double (64-bit number), Date, String, and variant.

Variables declared with Dim at the module level are available to all procedures within the module. At the procedure level, variables are available only within the procedure.

Dim FullName As String
Dim Age As Integer
Dim Weight As Double
  
FullName = "Mike Prestwood"
Age = 32
Weight = 154.4
 
'Declaritive assignment not supported:
''Dim Married As String = "Y"   '>>>Not supported.



Topic: Language Basics

-Collapse +Expand 264. VB Classic Logical Operators (and, or, not)
 

VB Classic logical operators:

and and, as in this and that
or or, as in this or that
Not Not, as in Not This

'Given expressions a, b, c, and d:
If Not (a and b) and (c or d) Then
  'Do something.
End If



Topic: Language Details

-Collapse +Expand 265. VB Classic Associative Array (Collection)
 

In addition to Add and Item, collections also offer Count and Remove. Notice that Add uses the format of Value, Key (which is backwards from many other languages).

Dim States As New Collection
   
States.Add "California", "CA"
States.Add "Nevada", "NV"
    
MsgBox (States.Item("CA"))
-Collapse +Expand 266. VB Classic Class..Object (Yes)
 

One class per file. File must use a .cls extension (instead of .bas). You can include your classes in your project (a traditional OOP approach) or compile them to a DLL or ActiveX EXE, register them, and use them that way (a uniquely VB approach).

-Collapse +Expand 267. VB Classic Custom Routines (Sub, Function)
 

VB Classic is a non-OOP language with some OOP features. It offers both Subs and Functions. A Sub does not return a value while a Function does. When Subs and Functions are used in a class module, they become the methods of the class.

Sub DoSomething(ByVal pMessage As String)
  MsgBox (pMessage)
End Sub
 
Function GetAge(ByRef pFullname As String) As Integer
  GetAge = 7
End Function
-Collapse +Expand 268. VB Classic Overloading (Not Supported)
 

Developer defined overloading in VB Classic:

  • Operator - No
  • Method - No
-Collapse +Expand 269. VB Classic Self Keyword (Me)
 

The Me keyword is a built-in variable that refers to the class where the code is executing. For example, you can pass Me from one module to another.

Private Sub Command4_Click()
  MsgBox Me.Name 'Displays name of form (Form1 in this case).
End Sub



Topic: Commands

-Collapse +Expand 270. VB Classic Left of String
 

VB Classic Left of String

Dim LeftString As String
LeftString = Left("Prestwood", 3)
MsgBox LeftString



Topic: OOP

-Collapse +Expand 271. VB Classic Constructors (Class_Initialize)
 

When an object instance is created from a class, VB6 calls a special parameter-less sub named Class_Initialize. Since you cannot specify parameters for this sub, you also cannot overload it.

When a class is destroyed, VB6 calls a special sub called Class_Terminate.

-Collapse +Expand 272. VB Classic Destructor
 

When an object instance is destroyed, VB6 calls a special parameter-less sub named Class_Terminate. For example, when the variable falls out of scope. Since you cannot specify parameters for this sub, you also cannot overload it.

When an object instance is created from a class, VB6 calls a special sub called Class_Initialize.

-Collapse +Expand 273. VB Classic Inheritance (No, but see Implements.)
 

VB classic supports only a single "level" of interface inheritance (abstract class to implimentation class). See Implements in VB's help.

-Collapse +Expand 274. VB Classic Inheritance-Multiple (Not Supported)
 

VB classic supports only a single "level" of inheritance (abstract class to implimentation class).

-Collapse +Expand 275. VB Classic Interfaces
 

VB6 has limited support for interfaces. You can create an interface of abstract methods and properties and then implement them in one or more descendant classes. It's a single level implementation though (you cannot inherit beyond that). The parent interface class is a pure abstract class (all methods and properites are abstract, you cannot implement any of them in the parent class).

In the single level descendant class, you have to implement all methods and properties and you cannot add any. Your first line of code is Implements InterfaceName.

-Collapse +Expand 276. VB Classic Member Method (sub, function)
 

VB classic uses the keywords sub and function. A sub does not return a value and a function does. Many programmers like to use the optional call keyword when calling a sub to indicate the call is to a procedure.

-Collapse +Expand 277. VB Classic Member Visibility
 

In VB Classic, the keywords Private, Friend, Public, and Static are used to set access levels for declared elements.




Group: ASP Classic Coding





Topic: ASP Classic

-Collapse +Expand 278. ASP Classic Array (x = Array())
 

Arrays in ASP Classic use a 0-based indice.

Use UBound to get the number of elements. UBound returns -1 if the array has no elements, 0 if it has 1, 1 if it has 2, etc.

Dim MyArray, i
 
MyArray = Array("Mike", "Lisa", "Felicia", "Nathan")
 
If UBound(MyArray) > -1 Then
  For i = 0 to UBound(MyArray)
    Response.Write MyArray(i)
  Next
End If
-Collapse +Expand 279. ASP Classic Case Sensitivity (No)
 

ASP Classic is not case sensitive. My preference for all languages where case sensitivity does not matter is to use camel caps as in the first example above. Many developers coming from a case sensitive language prefer to use all lowercase.

You can use any of the following:

Response.Write "Hello"
response.write "Hello"
RESPONSE.WRITE "Hello"
REsponse.WritE "Hello"
-Collapse +Expand 280. ASP Classic Edit Record (AddNew, Update, Delete)
 

In ASP, using ADO, you use RecordSet.AddNew to add a new record, Recordset.Update to post the record, and RecordSet.Delete to delete it. To edit a record, you open the RecordSet using an editable cursor.

The following code snippet adds a record to a given editable RecordSet with FullName and Created fields:

objRS.AddNew
objRS.Fields("FullName") = "Barack Obama"
objRS.Fields("Created")  = Now
objRS.Update
-Collapse +Expand 281. ASP Classic Empty String Check (Len(s&vbNullString))
 

In ASP Classic, you have to add an empty string to the value being compared in order to get consistent results. For example, add &"" to your string varilable or it's code equivalent &vbNullString. Then compare to an empty string or verify it's length to 0 with Len.

All these will work for variables unassigned, set to "", or set to Null:

If s&"" = "" Then
  Response.Write("<br>Quotes with &'' say null is empty")
End If
 
If Len(s&"") = 0 Then
  Response.Write("<br>Len with &'' says null is empty")
End If
 
If Len(s&vbNullString) = 0 Then
  Response.Write("<br>Using vbNullString also works!")
End If
-Collapse +Expand 282. ASP Classic Exception Trapping (On Error)
 

Languages Focus: Exception Trapping

A common usage of exception handling is to obtain and use resources in a "try-it" block, deal with any exceptions in an "exceptions" block, and release the resources in some kind of "final" block which executes whether or not any exceptions are trapped.

ASP Classic Exception Trapping

On Error Resume Next
Response.Write FormatDateTime(f_CurrentActualDate, vbShortDate)
  
  If ErrNumber <> 0 Then
Break(f_CurrentActualDate)
End If
On Error Goto 0
-Collapse +Expand 283. ASP Classic File Extensions (.ASP)
 

.asp is the default extension for Active Server Pages (ASP) although some developers will change the default extension in an effort to add an additional security level. Although there is no clear standard for include files, using .INC is common but you must make sure that .INC files are not executed nor displayed.

-Collapse +Expand 284. ASP Classic Filter Records (Filter)
 

In ASP, using ADO, you filter a set of records using Filter.

objRecordSet.Filter = "ExtEmpType='P'"
-Collapse +Expand 285. ASP Classic Find Record (Find, Seek)
 

In ASP, using ADO, you use Find and Seek to move a cursor of a RecordSet to a matching record.

Given a valid ADO recordset, the following code snippet finds a specific user and prints out their age:

TC.Find " UserID='mprestwood' "
Response.Write TC.Fields("Age")
-Collapse +Expand 286. ASP Classic Parameters (ByRef, ByVal)
 

By Reference or Value
For parameters, you can optionally specify ByVal or ByRef. ByRef is the default if you don't specify.

Function SomeRoutine(ByRef pPerson, ByVal pName, Age)
-Collapse +Expand 287. ASP Classic Record Movement (MoveFirst, MoveLast, MoveNext)
 

ASP uses MoveFirst, MoveLast, MoveNext, and MovePrevious to move a database cursor (a RecordSet).

objRecordSet.MoveNext

The following snippet moves to the second to last record of a given RecordSet object:

objRecordSet.MoveLast
objRecordSet.MovePrevious
-Collapse +Expand 288. ASP Classic Sort Records (Sort)
 

In ASP, using ADO, you sort a set of records using the Sort property.

objMembersRS.Sort = "FirstName"
-Collapse +Expand 289. ASP Classic Yes/No Function
 

The following function demonstrates one technique for coding a Yes/No dropdown. It uses a for loop which can be expanded to handle more than the 3 states (Y, N, and blank).

Example of calling the function:

Do you fish? &lt;%=YesNoDropDown("ynFish", "")%&gt;
Function YesNoDropDown(strName, strSelected) 
 Dim i
 Dim strSelectedString
 Dim YesNoName
 Dim YesNoCode
 YesNoName = Array("Yes","No")  
 YesNoCode = Array("Y","N")
 
 YesNoDropDown = "<select name='" & strName & "'>" & vbcrlf
 YesNoDropDown = YesNoDropDown & "<option>" & "--" & "</option>"
 
 For i = 0 To UBound(YesNoName)  
  If strSelected = YesNoCode(i) Then    
   strSelectedString = "Selected"  
  Else    
   strSelectedString = ""  
  End If          
  
  YesNoDropDown = YesNoDropDown & "<option value='" & YesNoCode(i) & "' " & _      
  strSelectedString & " >" & YesNoName(i) & "</option>" & vbcrlf 
 Next      
 
 YesNoDropDown = YesNoDropDown & "</select>" & vbcrlf 
End Function

 
-Collapse +Expand 290. DateDiff vbMonday ww Week of Year
 
This code returns the current week of the current year with a week starting on Monday.
DateDiff("ww", CDate("1/1/" & Year(Now)), Now, vbMonday)
-Collapse +Expand 291. How do I determine which version of IIS I am running?
 
The following ASP Classic code displays the version of the Internet Information Services (IIS) you are running in the form of a text string (i.e. Microsoft-IIS/6.0).
response.write(Request.ServerVariables("SERVER_SOFTWARE")) 



Topic: Tool Basics

-Collapse +Expand 292. ASP Classic Assignment (=)
 

ASP Classic uses = for it's assignment operator.

FullName = "Randy Spitz"
Age = 38
-Collapse +Expand 293. ASP Classic Code Blocks (End Xxx)
 

In .ASPhtml pages, you embed ASP code between <% and %>.

ASP Classic code blocks are surrounded by statement ending keywords that all use End such as End Sub, End If, and WEnd.

<%
Sub x
End Sub
 
If x Then
End If
 
While x
WEnd
%>
-Collapse +Expand 294. ASP Classic Comments (' or REM)
 

Commenting Code
ASP Classic, like all the VB-based languages, uses a single quote (') or the original class-style basic "REM" (most developers just use a quote). ASP Classic does NOT have a multiple line comment.

Preprocessor Directives - @ and #
An @ is used for preprocessor directives within ASP code (within <% %>) and a # is used for HTML-style preprocessor directives.

Note: ASP Classic does not support VB Classic's #If directive.

'Single line comment.
REM Old school single line comment.

 

Common Preprocessor Directives include:

<%@LANGUAGE=VBScript%>
<!-- #Include File="includes.inc" -->
-Collapse +Expand 295. ASP Classic Comparison Operators (=, <>)
 

Save as VB Classic.

//Does ASP evaluate the math correctly? No!
If .1 + .1 + .1 = .3 Then
Response.Write "correct"
Else
Response.Write "not correct"
End If
-Collapse +Expand 296. ASP Classic Deployment Overview
 

With ASP Classic, you simply copy your files to a web server that is capable of running ASP pages. This includes your .ASP pages along with supporting files such as images, include files, and database files.

Optionally, you can also deploy a global.asa file which is used to code certain events like application start, application end, session start, and session end.

-Collapse +Expand 297. ASP Classic Development Tools
 

Languages Focus: Development Tools

Primary development tool(s) used to develop and debug code.

ASP Classic Development Tools

Microsoft Visual Interdev was popular for several  years but isn't used as much any more. Any good editor such as Microsoft Expression Web, etc. will work but debugging is left up to interactive skills.

-Collapse +Expand 298. ASP Classic End of Statement (Return)
 

Languages Focus: End of Statement

In coding languages, common End of statement specifiers include a semicolon and return (others exist too). Also of concern when studying a language is can you put two statements on a single code line and can you break a single statement into two or more code lines.

ASP Classic End of Statement

A return marks the end of a statement and you cannot combine statements on a single line of code. You can break a single statement into two or more code lines by using a space and underscore " _".

Response.Write("Hello1")
Response.Write("Hello2")
Response.Write("Hello3")

'The following commented code on a single line does not work...
' Response.Write("Hello4") Response.Write("Hello5")

'Two or more lines works too with a space+underscore:
Response.Write _
("Hello6")
-Collapse +Expand 299. ASP Classic Literals (quote)
 

Literals are quoted as in "Prestwood".  If you need to embed a quote use two quotes in a row.

Response.Write "Hello"
Response.Write "Hello ""Mike""."
  
'Does ASP evaluate this simple
'floating point math correctly? No! 
If (.1 + .1 + .1) = .3 Then
 Response.Write "Correct"
Else
 Response.Write "Not correct"
End If
-Collapse +Expand 300. ASP Classic Overview and History
 

Language Overview: Class-based language. Although you can create classes, ASP is not fully OOP. It is a traditional language with a few OOP extensions. You code in a traditional approach using functions, procedures, and global data, and you can make use of simple classes to help organize your reusable code.

Target Platforms: ASP Classic is most suitable for creating websites targeting any browser (IIS Web Server with ASP Classic installed or equivalent).

-Collapse +Expand 301. ASP Classic Report Tools Overview
 

Because ASP Classic targets a client browser (a document interfaced GUI), a common solution is to simply output an HTML formatted page with black text and a white background (not much control but it does work for some situations).

-Collapse +Expand 302. ASP Classic String Concatenation (& or +)
 

Although you can use either a & or a + to concatenate values, my preference is to use a + because more languages use it. However, if you use & then some type conversions are done for you. If you use + you will sometimes have to cast a value to concatenate it. For example, you will have to use CStr to cast a number to a string if you use the + operator as a concatenation operator.

Dim FirstName
Dim LastName
 
FirstName  = "Mike"
LastName  = "Prestwood"
 
Response.Write "Full name: " & FirstName & " " + LastName
 
Response.Write "2+2=" + CStr(2+2)
-Collapse +Expand 303. ASP Classic Unary Operators
 

An operation with only one operand (a single input) such as + and -.

-Collapse +Expand 304. ASP Classic Variables (Dim x)
 

ASP Classic is a loosely typed language. No variable types in ASP (all variables are variants). Declaring variables is even optional unless you use the Option Explicit statement to force explicit declaration of all variables with Dim in that script. Using Option Explicit is strongly recommended to avoid incorrectly typing an existing variable and to avoid any confusion about variable scope.

For example, at the top of my common include file, I have the following:

<%@LANGUAGE=VBScript%>
<%
Option Explicit
'...more code here.
%>
Dim Fullname
Dim Age
Dim Weight
 
FullName = "Mike Prestwood"
Age = 32
Weight = 154.4
 
'Declaritive assignment not supported:
''Dim Married = "Y"   '>>>Not supported.
-Collapse +Expand 305. Response.Write Assignment Operator
 
This is a simple example of passing a value to a JavaScript function. You can pass values to JavaScript the same way you pass values to HTML.
<%
Dim MyName
MyName = "Mr Paradiddle"
%>
<script language="javascript">
<!--
function ShowYourName() {
document.write('Your name is <%=MyName%>.')
}
ShowYourName()
-->
</script>



Topic: Language Basics

-Collapse +Expand 306. ASP Classic Constants (Const kPI = 3.1459)
 

Scope can be Public or Private. Public Const is the same as just specifying Const. As with variables, all constants are variants. You do not specify the type, it's implied.

Const kPI = 3.1459
Const kName = "Mike"
 
//Public variable:
Public Const kFeetToMeter=3.28, kMeterToFeet=.3
-Collapse +Expand 307. ASP Classic If Statement (If..ElseIf..Else..End If)
 

The End If is optional if you put your code on a single line.

//Single line example.
If X = True Then Response.Write "hello" 
  
//Complete example.
If X = True Then
  '>>>do something.
ElseIf Y = "ABC" Then
  '>>>do something.
Else
  '>>>do something.
End If
-Collapse +Expand 308. ASP Classic Left
 
Dim LeftString
LeftString = Left("Prestwood", 3)
Response.Write LeftString
-Collapse +Expand 309. ASP Classic Logical Operators (and, or, not)
 

Same as VB. ASP Classic logical operators:

and and, as in this and that
or or, as in this or that
Not Not, as in Not This

'Given expressions a, b, c, and d:
If Not (a and b) and (c or d) Then
  'Do something.
End If
-Collapse +Expand 310. ASP redirect http to https
 

To redirect from http to https, check the Request.ServerVariables HTTPS field and then use Response.Redirect if set to "off".

Here's a code snippet:

If Request.ServerVariables("HTTPS") = "off" Then 
  Response.Redirect https://store.prestwood.com
End If

Obviously this code works only for "specific" implementations. You could make this non-domain specific pretty easily by "constructing" the https://www.prestwood.com portion.

-Collapse +Expand 311. CBool(ANumber Mod 2)
 
The following function returns true if the integer portion of a number passed in is odd; otherwise, it returns false.
Function IsOdd(byVal ANumber)
 ''Non numbers always return false.
 If Not IsNumeric(ANumber) Then 
  IsOdd = False
  Exit Function
 End If
 ANumber = Fix(ANumber)  '>>>Strip to integer.
 
 IsOdd = CBool(ANumber Mod 2)
End Function
-Collapse +Expand 312. GetStringCount with Split and UBound
 

This function uses Split to count the number of strings within a string.

Function GetStringCount(AString, AChar)
 Dim MyArray
 Dim ArrayCount
 
 MyArray = Split(AString, AChar)
 
 GetStringCount = UBound(MyArray)
End Function
-Collapse +Expand 313. Random Numbers with Rnd and Randomize
 
Call randomize then call Rnd to generate a random number between 0 and 1. The following generates a random number from the low to high number including the low and high numbers:

Function GetRandomInt(LowNumber, HighNumber)
RANDOMIZE
GetRandomInt = Round(((HighNumber-1) - LowNumber+1) * Rnd+LowNumber)
End Function

Response.Write GetRandomInt(10, 100)

-Collapse +Expand 314. Scripting.FileSystemObject
 
The following function uses the Scripting.FileSystemObject to check for the existence of a file.
Function IsFileExists(AFileName)
 Dim objFSO
 Dim TempFileName
 
 TempFileName = Server.MapPath(TempFileName)
 Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
   
 If (objFSO.FileExists( TempFileName ) = True)  Then
  IsFileExists = True
 Else
  IsFileExists = False
 End If
 
 Set objFSO = Nothing
End Function
-Collapse +Expand 315. Scripting.FileSystemObject
 
The following function uses the FileSystemObject to delete a file.

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' DeleteFile
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function DeleteFile(AFileName)
 Dim objFSO
 Dim TempFileName
 
 TempFileName = AFileName
 
 Set objFSO = Server.CreateObject("Scripting.FileSystemObject")  
 Call objFSO.DeleteFile(Server.MapPath(TempFileName), True) 

 Set objFSO = Nothing  
End Function




Topic: Language Details

-Collapse +Expand 316. ASP Classic Associative Array (Scripting.Dictionary)
 

Use the scriptiing dictionary object which is available on later versions of ASP Classic (all still commonly in use). Both Access VBA and VB Classic use a collection for this but collections are not supported in ASP Classic.

Dim StateList
Set StateList = Server.CreateObject("Scripting.Dictionary")
StateList.Add "CA", "California"
StateList.Add "NV", "Nevada" 
Response.Write "I live in " & StateList.Item("CA")
Dim StateList
 
set StateList = Server.CreateObject("Scripting.Dictionary")
StateList.Add "CA", "California"
StateList.Add "NV", "Nevada"
 
Response.Write "I live in " & StateList.Item("CA")
-Collapse +Expand 317. ASP Classic Custom Routines (Sub, Function)
 

ASP Classic is a non-OOP language with some OOP features. It offers both Subs and Functions. A Sub does not return a value while a Function does. When Subs and Functions are used in a defined class, they become the methods of the class.

Sub SayHello(ByVal pName)
  Response.Write "Hello " + pName + "!<br>"
End Sub
 
Function Add(ByRef pN1, ByRef pN2)
  Add = pN1 + pN2
End Function
-Collapse +Expand 318. ASP Classic Overloading (Not Supported)
 

ASP Classic does not support any type of overloading.

  • Operator - No.
  • Method - No.

Some developers like to pass in an array and then handle the array for a pseudo technique. Although not overloading, it's useful.

-Collapse +Expand 319. ASP Classic Self Keyword (me)
 

Same as VB. The Me keyword is a built-in variable that refers to the class where the code is executing.

Class Cyborg
 Public CyborgName
 
 Public Function IntroduceYourself() 
  'Using Me. Prints Cameron.
  Response.Write("Hi, my name is " & Me.CyborgName & ".")
  
  'The above is just a demo. You could also not include "Me." 
  'in this case because we are in context of Me now. Using Me 
  'makes more sense when you start to pass Me as a parameter 
  'to a method.
 End Function 
End Class



Topic: OOP

-Collapse +Expand 320. ASP Classic Class..Object (Class..Set..New)
 

Ultra-primitive (no inheritance) but useful and encourages you to think and design using objects.

'Declare class.
Class Cyborg
  Public Function IntroduceYourself() 
    Response.Write("Hi, I do not have a name yet.") 
  End Function 
End Class
 
'Create object from class.
Set T1 = new Cyborg
T1.IntroduceYourself() 
Set T1 = Nothing      'Be sure to clean up!
-Collapse +Expand 321. ASP Classic Constructors (Class_Initialize)
 

When an object instance is created from a class, ASP calls a special parameter-less sub named Class_Initialize. Since you cannot specify parameters for this sub, you also cannot overload it.

When a class is destroyed, ASP calls a special sub called Class_Terminate.

Class Cyborg
  Public CyborgName
 
 Public Sub Class_Initialize
   Response.Write "<br>Class created"
   CyborgName = "Cameron"
  End Sub 
End Class
-Collapse +Expand 322. ASP Classic Destructor (Class_Terminate)
 

When an object instance is destroyed, ASP calls a special parameter-less sub named Class_Terminate. For example, when the variable falls out of scope. Since you cannot specify parameters for this sub, you also cannot overload it.

When an object instance is created from a class, ASP calls a special sub called Class_Initialize.

Class Cyborg
  Public Sub Class_Terminate
    Response.Write "<br>Class destroyed"
End Sub
End Class
-Collapse +Expand 323. ASP Classic Inheritance (Not Supported)
 

General Info: Inheritance

The concept of a class makes it possible to define subclasses that share some or all of the main class characteristics. This is called inheritance. Inheritance also allows you to reuse code more efficiently. In a class tree, inheritance is used to design classes vertically. (You can use Interfaces to design classes horizontally within a class tree.) With inheritance, you are defining an "is-a" relationship (i.e. a chow is-a dog). Analysts using UML call this generalization where you generalize specific classes into general parent classes.

ASP Classic Inheritance

-Collapse +Expand 324. ASP Classic Interfaces (Not Supported)
 

Although ASP Classic does support simple classes, it does not support interfaces.

-Collapse +Expand 325. ASP Classic Member Field
 

ASP Classic does support member fields, but, as usual, you cannot initialize the type nor value of a member field. The type is implied by usage.

Class Cyborg
  Private FSerialNumber
  
  Public FCyborgName
  Public FCyborgAge 
Public FSeriesID
End Class
-Collapse +Expand 326. ASP Classic Member Method (Sub, Function)
 

ASP classic uses the keywords sub and function. A sub does not return a value and a function does. Many programmers like to use the optional call keyword when calling a sub to indicate the call is to a procedure.

'Declare class.
Class Cyborg
  Public Function IntroduceYourself() 
    Response.Write("Hi, I do not have a name yet.") 
  End Function 
End Class
 
'Create object from class.
Set T1 = new Cyborg
T1.IntroduceYourself() 
-Collapse +Expand 327. ASP Classic Member Modifiers (Default)
 

Other than visibility modifiers Public and Private, the only other member modifier available in ASP Classic is Default which is used only with the Public keyword in a class block. It indicates that the sub, function, or property is the default method for the class. You can have only one Default per class.

-Collapse +Expand 328. ASP Classic Member Property (Property..Get..Let)
 

ASP classic uses the property keyword and special Get and Let methods to both get and set the values of properties.

Class Cyborg
 Private FCyborgName
 
 Public Property Get CyborgName()
  CyborgName = FCyborgName
 End Property
 
 Public Property Let CyborgName(pCyborgName)
  FCyborgName = pCyborgName
 End Property
End Class
-Collapse +Expand 329. ASP Classic Member Visibility (Private, Public)
 

The member visibility modifiers are Private and Public. If not specified, the default is Public. Private and Public have the usual meaning. Private members are visible only within the class block. Public members are visible within the class and outside of the class.

Class Cyborg
  Private FSerialNumber  
  Public FCyborgName
  
  Public Function IntroduceYourself() 
Response.Write("Hi, I do not have a name yet.")
End Function
End Class
-Collapse +Expand 330. ASP Classic Static Members (Not Supported)
 

Although ASP Classic supports the creation of simple classes, it does not support static methods.




Group: Website Design & Hosting





Topic: Cascading Style Sheets (CSS)

-Collapse +Expand 331. CSS Import URL
 
The following code snippet allows you to import a cascading style sheet (CSS) into another CSS file. The main benefit is this allows you to organize your styles and to create common CSS files.

@import url('/style_core.css');




Group: Java





Topic: Java

-Collapse +Expand 332. Java Abstraction (abstract)
 

Java supports marking a full class as abstract as well as class members. A subclass must either implement the abstract members or you must declare the subclass abstract (which delays the implementation to it's subclass).

public abstract class Dog {
  abstract void Bark();
}
-Collapse +Expand 333. Java Case Sensitivity (Yes)
 

Java is case sensitive.

Customary casing:

  • Classes - Initial Caps (Pascal Casing)
  • Variables - Initial lowecase (Camel case)
  • Methods - Initial lowecase (Camel case)
-Collapse +Expand 334. Java Comparison Operators (==, !=)
 

The Java comparison operators are:

  • < less than
  • <= less than or equal to
  • == equal to
  • >= greater than or equal to
  • > greater than
  • != not equal
-Collapse +Expand 335. Java Exception Trapping (try/catch/finally)
 

Languages Focus: Exception Trapping

A common usage of exception handling is to obtain and use resources in a "try-it" block, deal with any exceptions in an "exceptions" block, and release the resources in some kind of "final" block which executes whether or not any exceptions are trapped.

Java Exception Trapping

try {
  /* Risky code here. */
}
catch (SomeException) {        //one or more.
  /* Recovery here. */
}
finally {                      //0 or one.
  /* Do something. */
}
-Collapse +Expand 336. Java File Extensions (.java)
 

The customary primary source file extension for Java code is ".java" which could contain anywhere from a single class to the entire source code.

Other important files:

  • .JAR - Java archive file (compressed code file). Archive that contains multiple Java files and is compressed using .ZIP compression; stores Java classes and metadata and may be digitally signed; runs as a program if the Java Runtime Environment (JRE) is installed on the computer.
  • .CLASS - compiled source code which are platform-independent. If a source file has more than one class, each class is compiled into a separate .class file. These .class files can be loaded by any Java Virtual Machine (JVM).
-Collapse +Expand 337. Java Static Members (static)
 

When calling a static method from within the same class, you don't need to specify the class name.

class MyUtils {
//Static method.
  public static void MyStaticMethod() {
}
}



Topic: Tool Basics

-Collapse +Expand 338. Java Code Blocks ({ })
 

Curly braces are used to bracket code blocks including classes and the methods within a class.

For Java, JavaScript, PHP, and C++, I prefer to put the first { at the end of the first line of the code block as in the example above because I see moreJava codeformatted that way.

public class Dog {
  public bark() {
    System.out.println("Ruff");
  }
}
-Collapse +Expand 339. Java Comments (// or /* ... */)
 

Commenting Code
Java uses "//" for a single line comment and /* */ for a multiple line comment.

//Single line comment in MS (not ANSI compliant so do NOT use).
/* ANSI compliant single line comment. */
/*
Multiple line
comment.
*/
/*
* This is another popular way 
* to write multi-line comments.
*/
-Collapse +Expand 340. Java Deployment Overview
 

Java applets and applications both require the Java Runtime Environment (JRE) and any additional dependencies you've added.

-Collapse +Expand 341. Java Development Tools
 

Languages Focus: Development Tools

Primary development tool(s) used to develop and debug code.

Java Development Tools

Many compilers and development tools are available. Common development tools include Sun's J2EE, CodeGear JBuilder, and Eclipse.

-Collapse +Expand 342. Java Literals (quote)
 

Literals are quoted as in "Prestwood". If you need to embed a quote use a slash in front of the quote as in \".

System.out.println("Hello");
System.out.println("Hello \"Mike\".");
  
//Does Java evaluate this simple
//floating point math correctly? No!
if ((.1 + .1 + .1) == 0.3) {
System.out.println("Correct");
} else {
System.out.println("Not correct");
}
-Collapse +Expand 343. Java Overview and History
 

Promoted as a single source cross-platform runtime system (Write Once, Run Anywhere). Java builds on and in some ways simplifies the object oriented features of C++. Java applications are typically compiled to byte-code and can run on any platform running the Java Virtual Machine (JVM).

Target Platforms: Java is suitable for creating many types of cross-platform applications that target the JVM including desktop business applications.

-Collapse +Expand 344. Java Report Tools Overview
 

Both Eclipse 3.3 and JBuilder 2008 come bundled with Business Intelligence and Reporting Tools (BIRT). BIRT is an Eclipse-based open source reporting system with both a report designer based on Eclipse, and a runtime component that you can add to your app server plus a charting engine that lets you add charts.

-Collapse +Expand 345. Java String Concatenation (+ or append)
 

Java String Concatenation

In Java, you use either the String concatenation + operator or StringBulder class methods such as append. Since Java compilers frequently create intermediate objects when the + operator is used and don't when StringBuilder.append is used, the append method is faster than the + operator.

In general, use the convenience of a + operator when speed is not an issue. For example, when concatenating a small number of items and when code isn't executed very frequently. A decent rule of thumb is to use the + operator for general purpose programming and then optimize the + operator with StringBuilder.append as needed.

Simple + operator example:

System.out.println("Hello" + " " + "Mike.");

 

Using StringBuilder example:

StringBuilder myMsg = new StringBuilder();

myMsg.append("Hello ");
myMsg.append("Mike.");
 
System.out.println(myMsg);
-Collapse +Expand 346. Java Unary Operators
 

An operation with only one operand (a single input). The Java unary operators are ++, --, +, -, ~, and !.

  • + Indicates positive value (numbers are positive without this)
  • - Negates an expression
  • ++ Increment operator by 1
  • -- Decrement operator by 1
  • ! Logical complement operator (inverts the value of a boolean)
  • ~ Bitwise inversion operator (works on integral data types)
-Collapse +Expand 347. Java Variables (int x = 0;)
 

Variable names are case sensitive.

The Java basic types are boolean, byte, short, int, long, float, double, and char. You can also declare a variable to hold a particular instance of a class such as String.

C++, Java, and C# all use C-like variable declaration.

int a;
int a, b;
int age = 43;
String FullName;



Topic: Language Basics

-Collapse +Expand 348. Java If Statement (if..else if..else)
 

Syntax template:

if (expression) {
  expression1_true_code;
} else if (expression2) {
  expression2_true_code;
} else {
  otherwise_code;
}
if ((.1 + .1 + .1) == 0.3) {
  System.out.println("Correct");
} else {
  System.out.println("Not correct");
}
-Collapse +Expand 349. Java Logical Operators
 

Java logical operators:

&& and, as in this and that
|| or, as in this or that
! Not, as in Not This
& boolean logical OR (not short circuited)
| boolean logical OR (not short circuited)
?: Ternary (short for if-then-else)
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
^ Bitwise exclusiv OR

//Given expressions a, b, c, and d:
if !((a && b) && (c || d)) {
  //Do something.
}



Topic: Language Details

-Collapse +Expand 350. Java Associative Array (HashMap())
 

An associative array links a set of keys to a set of values. In Java, associative arrays are implemented as Maps.

This will print "Arizona."

import java.util.*;

public class Maps
{
    public static void main(String[] args)
    {
        Map states = new HashMap();
       
        states.put("CA", "California");
        states.put("FL", "Florida");
        states.put("AZ", "Arizona");

        System.out.println(states.get("AZ"));
    }
}
-Collapse +Expand 351. Java Class..Object (class..new)
 

Unlike languages such as C++ and Object Pascal, every line of code written in Java must occur within a class.

//Declare class.
public class Cyborg {
  //Fields.
  private String cyborgName;
  private int age;
 
  //Constructor.
  public Person() {
  cyborgName = "unknown";
  age = 0;
  }
}
//Create object from class.
Cyborg p = new Cyborg();
p.getClass(); //From the Object base class.
-Collapse +Expand 352. Java Custom Routines
 

Because java is an OOP language, all custom routines belong to a specific class and are therefore referred to as methods.

All methods in Java must return something so even with procedures, you return a "void".

public void sayHello(String pName) {
  System.out.println("Hello" + pName);
}
 

public int add(int p1, int p2) {
  return p1 + p2;
}
-Collapse +Expand 353. Java Inheritance (extends ParentClass)
 

Simple syntax example of class inheritance.

In the following example, a terminator T-600 is-an android. 

public class Android {
}
 
public class T-600 extends Android {
}
-Collapse +Expand 354. Java Inlining (Automatic)
 

The Java compiler automatically inlines when it determines  a benefit. The use of final methods is considered a compiler hint to tell the compiler to inline the method if beneficial.

-Collapse +Expand 355. Java Overloading
 

Java Overloading

  • Operator - No. Sun deliberately choose not include operator overloading in the Java language.
  • Method - Yes.



Topic: OOP

-Collapse +Expand 356. Java Base Class (Object)
 

The Object class is Java's single base class all classes ultimately inherit from.

public class Cyborg {
}

or you can specify the base class (or any other class):

public class Cyborg extends Object {
}
-Collapse +Expand 357. Java Constructors (Use class name)
 

A method with the same name as the class.

public class Cyborg{
  //Constructors have the same name as the class.
  public Cyborg() {
  }
}
-Collapse +Expand 358. Java final class (Final)
 

In Java, there is the concept of a final class.

-Collapse +Expand 359. Java finalize (finalize())
 

Java has a garbage collection algorythm that runs as a background task so it has no destructors. You can use the finalize() method to close additonal resources such as file handles.

protected void finalize() throws Throwable {
try {
close(); // close open files
} finally {
super.finalize();
}
}
-Collapse +Expand 360. Java Inheritance-Multiple (Interfaces Only)
 

Java does not support multiple implementation inheritance. Each class can have only one parent class (a single inheritance path). In Java, you can use multiple interface usage to design in a multiple class way horizontally in a class hierarchy.

-Collapse +Expand 361. Java Interfaces (Yes)
 

General Info: Interface

An element of coding where you define a common set of properties and methods for use with the design of two or more classes.

Both interfaces and abstract classes are types of abstraction. With interfaces, like abstract classes, you cannot provide any implementation. However, unlike abstract classes, interfaces are not based on inheritance. You can apply an Interface to any class in your class tree. In a real sense, interfaces are a technique for designing horizontally in a class hierarchy (as opposed to inheritance where you design vertically). Using interfaces in your class design allows your system to evolve without breaking existing code.

Java Interfaces

-Collapse +Expand 362. Java Member Field
 

In Java, you can set the scope of a field member to public, protected, or private. Additional modifiers are static, abstract, final (assign only once), strictfp (strict floating point values) transient (do not save to persistent storage), and volatile (all threads see same value).




Group: JavaScript and AJAX





Topic: Beginners Corner

-Collapse +Expand 363. JavaScript Assignment (=)
 

JavaScript uses = for it's assignment operator.

//Regular assignment.
LastName = 'Spitz';
  
//Variable declaration with assignment.
var FullName = 'Randy Spitz';
var Age = 38;
-Collapse +Expand 364. JavaScript Comments (// or /* ... */)
 

Commenting Code
JavaScript uses "//" for a single line comment and /* */ for a multiple line comment.

//This is a single line comment.

/*
Multiple line
comment.
*/
-Collapse +Expand 365. JavaScript Comparison Operators (==, !=)
 

Common comparison operators:

== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

//Does JavaScript evaluate the math correctly? No!
if (.1 + .1 + .1 == .3) {
document.write("correct");
}
else {
document.write("not correct");
}
-Collapse +Expand 366. JavaScript Development Tools
 

Languages Focus: Development Tools

Primary development tool(s) used to develop and debug code.

JavaScript Development Tools

Many developers just use a text editor. There are JavaScript editors available including 1st JavaScript Editor, Antechinus JavaScript Editor Professional, and SplineTech JavaScript Debugger PRO.

-Collapse +Expand 367. JavaScript End of Statement (; is optional)
 

In JavaScript, using a semicolon at the end of statements is optional. You might think a semicolon then is just another comment specifier but it is not. The semicolon is an optional end of statement specifier. To put two statements on a single code line, you must use a semicolon. However, the semicolon is optional, but probably confusing, when you break a single statement into multiple code lines.

document.write("Hello1");
document.write("Hello2");

//Semicolons are optional:
document.write("Hello3")