Saturday, September 29, 2007

Code Conventions for the JavaTM Programming Language Part 3

Declarations
6.1 Number Per Line
One declaration per line is recommended since it encourages commenting. In other words,

int level; // indentation level
int size; // size of table

is preferred over

int level, size;

Do not put different types on the same line. Example:


int foo, fooarray[]; //WRONG!


Note: The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs, e.g.:

int level; // indentation level
int size; // size of table
Object currentEntry; // currently selected table entry

6.2 Initialization
Try to initialize local variables where they're declared. The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first.

6.3 Placement
Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces "{" and "}".) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.

void myMethod() {
int int1 = 0; // beginning of method block

if (condition) {
int int2 = 0; // beginning of "if" block
...
}
}


The one exception to the rule is indexes of for loops, which in Java can be declared in the for statement:

for (int i = 0; i < maxLoops; i++) { ... }


Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:

int count;
...
myMethod() {
if (condition) {
int count = 0; // AVOID!
...
}
...
}

6.4 Class and Interface Declarations
When coding Java classes and interfaces, the following formatting rules should be followed:

No space between a method name and the parenthesis "(" starting its parameter list
Open brace "{" appears at the end of the same line as the declaration statement
Closing brace "}" starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the "}" should appear immediately after the "{"
class Sample extends Object {
int ivar1;
int ivar2;

Sample(int i, int j) {
ivar1 = i;
ivar2 = j;
}

int emptyMethod() {}

...
}

Methods are separated by a blank line

Statements
7.1 Simple Statements
Each line should contain at most one statement. Example:

argv++; // Correct
argc--; // Correct
argv++; argc--; // AVOID!

7.2 Compound Statements
Compound statements are statements that contain lists of statements enclosed in braces "{ statements }". See the following sections for examples.

The enclosed statements should be indented one more level than the compound statement.
The opening brace should be at the end of the line that begins the compound statement; the closing brace should begin a line and be indented to the beginning of the compound statement.
Braces are used around all statements, even single statements, when they are part of a control structure, such as a if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.
7.3 return Statements
A return statement with a value should not use parentheses unless they make the return value more obvious in some way. Example:

return;

return myDisk.size();

return (size ? size : defaultSize);


7.4 if, if-else, if else-if else Statements
The if-else class of statements should have the following form:

if (condition) {
statements;
}

if (condition) {
statements;
} else {
statements;
}

if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}


Note: if statements always use braces {}. Avoid the following error-prone form:

if (condition) //AVOID! THIS OMITS THE BRACES {}!
statement;

7.5 for Statements
A for statement should have the following form:

for (initialization; condition; update) {
statements;
}

An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form:

for (initialization; condition; update);

When using the comma operator in the initialization or update clause of a for statement, avoid the complexity of using more than three variables. If needed, use separate statements before the for loop (for the initialization clause) or at the end of the loop (for the update clause).


7.6 while Statements
A while statement should have the following form:

while (condition) {
statements;
}

An empty while statement should have the following form:

while (condition);

7.7 do-while Statements
A do-while statement should have the following form:

do {
statements;
} while (condition);

7.8 switch Statements
A switch statement should have the following form:

switch (condition) {
case ABC:
statements;
/* falls through */

case DEF:
statements;
break;

case XYZ:
statements;
break;

default:
statements;
break;
}

Every time a case falls through (doesn't include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the /* falls through */ comment.

Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later another case is added.


7.9 try-catch Statements
A try-catch statement should have the following format:

try {
statements;
} catch (ExceptionClass e) {
statements;
}

A try-catch statement may also be followed by finally, which executes regardless of whether or not the try block has completed successfully.

try {
statements;
} catch (ExceptionClass e) {
statements;
} finally {
statements;
}


--------------------------------------------------------------------------------

Friday, September 28, 2007

Code Conventions for the JavaTM Programming Language Part 2

4 - Indentation
Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4).

4.1 Line Length
Avoid lines longer than 80 characters, since they're not handled well by many terminals and tools.

Note: Examples for use in documentation should have a shorter line length-generally no more than 70 characters.

4.2 Wrapping Lines
When an expression will not fit on a single line, break it according to these general principles:

Break after a comma.
Break before an operator.
Prefer higher-level breaks to lower-level breaks.
Align the new line with the beginning of the expression at the same level on the previous line.
If the above rules lead to confusing code or to code that's squished up against the right margin, just indent 8 spaces instead.
Here are some examples of breaking method calls:

someMethod(longExpression1, longExpression2, longExpression3,
longExpression4, longExpression5);

var = someMethod1(longExpression1,
someMethod2(longExpression2,
longExpression3));

Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.

longName1 = longName2 * (longName3 + longName4 - longName5)
+ 4 * longname6; // PREFER

longName1 = longName2 * (longName3 + longName4
- longName5) + 4 * longname6; // AVOID

Following are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces.

//CONVENTIONAL INDENTATION
someMethod(int anArg, Object anotherArg, String yetAnotherArg,
Object andStillAnother) {
...
}

//INDENT 8 SPACES TO AVOID VERY DEEP INDENTS
private static synchronized horkingLongMethodName(int anArg,
Object anotherArg, String yetAnotherArg,
Object andStillAnother) {
...
}

Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example:

//DON'T USE THIS INDENTATION
if ((condition1 && condition2)
|| (condition3 && condition4)
||!(condition5 && condition6)) { //BAD WRAPS
doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS
}

//USE THIS INDENTATION INSTEAD
if ((condition1 && condition2)
|| (condition3 && condition4)
||!(condition5 && condition6)) {
doSomethingAboutIt();
}

//OR USE THIS
if ((condition1 && condition2) || (condition3 && condition4)
||!(condition5 && condition6)) {
doSomethingAboutIt();
}

Here are three acceptable ways to format ternary expressions:

alpha = (aLongBooleanExpression) ? beta : gamma;

alpha = (aLongBooleanExpression) ? beta
: gamma;

alpha = (aLongBooleanExpression)
? beta
: gamma;

5 - Comments
Java programs can have two kinds of comments: implementation comments and documentation comments. Implementation comments are those found in C++, which are delimited by /*...*/, and //. Documentation comments (known as "doc comments") are Java-only, and are delimited by /**...*/. Doc comments can be extracted to HTML files using the javadoc tool.

Implementation comments are meant for commenting out code or for comments about the particular implementation. Doc comments are meant to describe the specification of the code, from an implementation-free perspective. to be read by developers who might not necessarily have the source code at hand.

Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how the corresponding package is built or in what directory it resides should not be included as a comment.

Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves.

Note:The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer.

Comments should not be enclosed in large boxes drawn with asterisks or other characters.
Comments should never include special characters such as form-feed and backspace.

5.1 Implementation Comment Formats
Programs can have four styles of implementation comments: block, single-line, trailing, and end-of-line.

5.1.1 Block Comments
Block comments are used to provide descriptions of files, methods, data structures and algorithms. Block comments may be used at the beginning of each file and before each method. They can also be used in other places, such as within methods. Block comments inside a function or method should be indented to the same level as the code they describe.

A block comment should be preceded by a blank line to set it apart from the rest of the code.

/*
* Here is a block comment.
*/

Block comments can start with /*-, which is recognized by indent(1) as the beginning of a block comment that should not be reformatted. Example:

/*-
* Here is a block comment with some very special
* formatting that I want indent(1) to ignore.
*
* one
* two
* three
*/


Note: If you don't use indent(1), you don't have to use /*- in your code or make any other concessions to the possibility that someone else might run indent(1) on your code.
See also "Documentation Comments" on page 9.


5.1.2 Single-Line Comments
Short comments can appear on a single line indented to the level of the code that follows. If a comment can't be written in a single line, it should follow the block comment format (see section 5.1.1). A single-line comment should be preceded by a blank line. Here's an example of a single-line comment in Java code (also see "Documentation Comments" on page 9):

if (condition) {

/* Handle the condition. */
...
}

5.1.3 Trailing Comments
Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting.

Here's an example of a trailing comment in Java code:

if (a == 2) {
return TRUE; /* special case */
} else {
return isPrime(a); /* works only for odd a */
}

5.1.4 End-Of-Line Comments
The // comment delimiter can comment out a complete line or only a partial line. It shouldn't be used on consecutive multiple lines for text comments; however, it can be used in consecutive multiple lines for commenting out sections of code. Examples of all three styles follow:

if (foo > 1) {

// Do a double-flip.
...
}
else {
return false; // Explain why here.
}
//if (bar > 1) {
//
// // Do a triple-flip.
// ...
//}
//else {
// return false;
//}

5.2 Documentation Comments
Note: See "Java Source File Example" on page 19 for examples of the comment formats described here.

For further details, see "How to Write Doc Comments for Javadoc" which includes information on the doc comment tags (@return, @param, @see):

http://java.sun.com/javadoc/writingdoccomments
For further details about doc comments and javadoc, see the javadoc home page at:

http://java.sun.com/javadoc/
Doc comments describe Java classes, interfaces, constructors, methods, and fields. Each doc comment is set inside the comment delimiters /**...*/, with one comment per class, interface, or member. This comment should appear just before the declaration:

/**
* The Example class provides ...
*/
public class Example { ...

Notice that top-level classes and interfaces are not indented, while their members are. The first line of doc comment (/**) for classes and interfaces is not indented; subsequent doc comment lines each have 1 space of indentation (to vertically align the asterisks). Members, including constructors, have 4 spaces for the first doc comment line and 5 spaces thereafter.

If you need to give information about a class, interface, variable, or method that isn't appropriate for documentation, use an implementation block comment (see section 5.1.1) or single-line (see section 5.1.2) comment immediately after the declaration. For example, details about the implementation of a class should go in in such an implementation block comment following the class statement, not in the class doc comment.

Doc comments should not be positioned inside a method or constructor definition block, because Java associates documentation comments with the first declaration after the comment.



--------------------------------------------------------------------------------

Monday, September 24, 2007

Code Conventions for the Java Programming Language

This Code Conventions for the Java Programming Language document contains the standard conventions that we at Sun follow and recommend that others follow. It covers filenames, file organization, indentation, comments, declarations, statements, white space, naming conventions, programming practices and includes a code example.

Why have code conventions? Code conventions are important to programmers for a number of reasons:

80% of the lifetime cost of a piece of software goes to maintenance.
Hardly any software is maintained for its whole life by the original author.
Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
The Code Conventions for the Java Programming Language document was revised and updated on April 20, 1999.


2 - File Names
This section lists commonly used file suffixes and names.

2.1 File Suffixes
Java Software uses the following file suffixes:

File Type

Suffix


Java source


.java



Java bytecode


.class




2.2 Common File Names
Frequently used file names include:

File Name

Use


GNUmakefile


The preferred name for makefiles. We use gnumake to build our software.



README


The preferred name for the file that summarizes the contents of a particular directory.





--------------------------------------------------------------------------------
3 - File Organization
A file consists of sections that should be separated by blank lines and an optional comment identifying each section.

Files longer than 2000 lines are cumbersome and should be avoided.

For an example of a Java program properly formatted, see "Java Source File Example" on page 19.

3.1 Java Source Files
Each Java source file contains a single public class or interface. When private classes and interfaces are associated with a public class, you can put them in the same source file as the public class. The public class should be the first class or interface in the file.

Java source files have the following ordering:

Beginning comments (see "Beginning Comments" on page 4)
Package and Import statements
Class and interface declarations (see "Class and Interface Declarations" on page 4)
3.1.1 Beginning Comments
All source files should begin with a c-style comment that lists the class name, version information, date, and copyright notice:

/*
* Classname
*
* Version information
*
* Date
*
* Copyright notice
*/

3.1.2 Package and Import Statements
The first non-comment line of most Java source files is a package statement. After that, import statements can follow. For example:

package java.awt;

import java.awt.peer.CanvasPeer;

Note: The first component of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.

3.1.3 Class and Interface Declarations
The following table describes the parts of a class or interface declaration, in the order that they should appear. See "Java Source File Example" on page 19 for an example that includes comments.



Part of Class/Interface Declaration

Notes


1


Class/interface documentation comment (/**...*/)


See "Documentation Comments" on page 9 for information on what should be in this comment.



2


class or interface statement






3


Class/interface implementation comment (/*...*/), if necessary


This comment should contain any class-wide or interface-wide information that wasn't appropriate for the class/interface documentation comment.



4


Class (static) variables


First the public class variables, then the protected, then package level (no access modifier), and then the private.



5


Instance variables


First public, then protected, then package level (no access modifier), and then private.



6


Constructors






7


Methods


These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.





--------------------------------------------------------------------------------

Saturday, September 22, 2007

Laern C# by practicale Part 5

Using Variables: A Word


Introduction


A word is a group of 16 consecutive bits. The bits are counted from right to left starting at 0:





Considered as a group of 16 bits, the most right bit of a word, bit 0, is called the least significant bit or Low Order bit or LO bit or LOBIT. The most left bit, bit 15, is called the most significant bit or High Order bit or HI bit or HIBIT. The other bits are referred to using their positions: bit 1, bit 2, bit 3, etc.

Considering that a word is made of two bytes, the group of the right 8 bits is called the least significant byte or Low Order byte or LO byte or LOBYTE. The other group is called the most significant byte or High Order byte or HI byte or HIBYTE.

The representation of a word in binary format is 0000000000000000. To make it easier to read, you can group bits by 4, like this: 0000 0000 0000 0000. Therefore, the minimum binary value represented by a word is 0000 0000 0000 0000. The minimum decimal value of a word is 0. The minimum hexadecimal value you can store in a word is 0x0000000000000000. This is also represented as 0x00000000, or 0x0000, or 0x0. All these numbers produce the same value, which is 0x0.

The maximum binary value represented by a word is 1111 1111 1111 1111. To find out the maximum decimal value of a word, you can use the base 2 formula, filling out each bit with 1:

1*215+1*214+1*213 + 1*212 + 1*211 + 1*210 + 1*29 + 1*28 + 1*27 + 1*26 + 1*25 + 1*24 + 1*23 + 1*22 + 1*21 + 1*20

= 32768 + 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1

= 65535

To find out the maximum hexadecimal number you can store in a word, replace every group of 4 bits with an f or F:

1111 1111 1111 1111
f f f f
= 0xffff
= 0xFFFF
= 0Xffff
= 0XFFFF


Short Integers



A word, which is a group of 16 contiguous bits or 2 bytes, can be used to hold a natural number. As we have studied, the maximum numeric value that can fit in a word is 65535. Since the byte is used to characters and very small numbers, whenever you plan to use a number in your program, the minimum representation you should use is a word.

A natural number is also called an integer. The smallest integer you can store in a word is declared with the short keyword followed by a name. Because a short integer is signed by default, it can store a value that ranges from –32768 to 32767. Here is an example program that uses two short integers:

using System;

class NumericRepresentation
{
static void Main()
{
short NumberOfPages;
short Temperature;

NumberOfPages = 842;
Temperature = -1544;

Console.Write("Number of Pages of the book: ");
Console.WriteLine(NumberOfPages);
Console.Write("Temperature to reach during the experiment: ");
Console.Write(Temperature);
Console.WriteLine(" degrees\n");
}
}
This would produce:

Number of Pages of the book: 842
Temperature to reach during the experiment: -1544 degrees
Because a short integer handles numbers that are larger than the signed byte, any variable you can declare for a signed byte can also be declared for a short variable.

Unsigned Short Integers



If a variable must hold positive and relatively small numbers, it is referred as an unsigned short integer. Such a variable can be declared using the ushort keyword. An unsigned short integer can hold numbers that range from 0 to 65535 and therefore can fit in 16 bits. Here is an example:

using System;

class NumericRepresentation
{
static void Main()
{
// These variables must hold only positive integers
ushort NumberOfTracks;
ushort MusicCategory;

NumberOfTracks = 16;
MusicCategory = 2;

Console.Write("This music album contains ");
Console.Write(NumberOfTracks);
Console.WriteLine(" tracks");
Console.Write("Music Category: ");
Console.Write(MusicCategory);
Console.WriteLine();
}
}
This would produce:

This music album contains 16 tracks
Music Category: 2
Practical Learning: Using Unsigned Short Integers



To use unsigned short integers, change the file as follows:
using System;

class Program
{
static void Main()
{
byte shirts;
byte pants;
ushort otherItems;

shirts = 4;
pants = 0;
otherItems = 3;

Console.WriteLine("-/- Georgetown Cleaning Services -/-");
Console.WriteLine("========================");
Console.WriteLine("Item Type Qty");
Console.WriteLine("------------------------");
Console.Write("Shirts ");
Console.WriteLine(shirts);
Console.Write("Pants ");
Console.WriteLine(pants);
Console.Write("Other Items ");
Console.WriteLine(otherItems);
Console.WriteLine("========================");
Console.WriteLine();
}
}


Execute the program. This would produce:
-/- Georgetown Cleaning Services -/-
========================
Order Date: 7/15/2002
------------------------
Item Type Qty
------------------------
Shirts 4
Pants 0
Other Items 3
========================

Press any key to continue . . .


Close the DOS window

Friday, September 21, 2007

Learn C# by Practicale Part 4

Using Variables: A Byte


Introduction


A byte is a group or eight consecutive bits. The bits are counted from right to left starting at 0:



The most right bit is bit 0; it is called the least significant bit. It is also referred to as the Low Order bit, the LO bit, or LOBIT.

The most left bit is bit 7; it is called the most significant bit. It is also referred to as the High Order bit, the HI bit, or HIBIT. The other bits are referred to following their positions:



Using the binary system, you can represent the byte using a combination of 0s and 1s. When all bits have a value of 0, the byte is represented as 00000000. On the other hand, when all bits have a value of 1, the byte is represented as 11111111. When the number grows very large, it becomes difficult to read. Therefore, you can represent bits in groups of four. Instead of writing 00000000, you can write 0000 0000. This makes the number easier to read.

If you have the patience to create combinations of bits using the cups as we did for the group of 4, you would find out that there are 256 possible combinations. Another way to find it out is by using the base 2 technique:

27 + 26 + 25 + 24 + 23 + 22 + 21 + 20
= 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1
= 255

Therefore, the maximum decimal value you can store in a byte is 255.

Remember that the byte with all bits having a value of 0 has its value set to 0. Since this byte also holds a valid value, the number of combinations = 255 + 1 = 256.

When a byte is completely represented with 0s, it provides the minimum value it can hold; this is 0000 0000, which is also 0. When all bits have a value of 1, which is 1111 1111, a byte holds its maximum value that we calculated as 255 in the decimal system. As done with the group of 4 bits, we get the following table:

Decimal Hexadecimal Binary
Minimum 0 0x0 0000
Maximum 255 0xff 1111 1111

The minimum storage area offered by the (Intel) computer is the byte. As you know already, a byte is a group of 8 consecutive bits. The amount of memory space offered by a byte can be used to store just a single symbol, such as those you see on your keyboard. These symbols, also called characters, have been organized by the American Standard Code for Information Exchange (ASCII) in a set list. But, ASCII uses only 128 decimal numbers (based on a 7-bit format) to represent symbols counted from 0 to 127. To compensate for the remaining 1 bit, IBM used it to organize special characters, foreign language characters, mathematical symbols, small graphics, etc. Each one of these characters has a decimal, a hexadecimal, and a binary equivalents.

Each one of the characters you see on your keyboard is represented as a numeric value, but whether it appears as a number, a letter, or a symbol, each one of these is considered a character. To display any character on your screen, you can pass it to Write() or WriteLine() and include the character between single-quotes, as follows:

using System;

class Exercise
{
static void Main()
{
Console.WriteLine('n');
}
}
Characters



In the English alphabet, a character is one of the following symbols: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z. Besides these readable characters, the following symbols are called digits and they are used to represent numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. In addition, some symbols on the (US QWERTY) keyboard are also called characters or symbols. They are ` ~ ! @ # $ % ^ & * ( ) - _ = + [ { ] } \ | ; : ' < ? . / , > "

Besides the English language, other languages use other or additional characters that represent verbal or written expressions.

C# recognizes that everything that can be displayed as a symbol is called a character. To declare a variable whose value would be a character, use the char keyword. Here is an example:

using System;

class ObjectName
{
static void Main()
{
char Gender = 'M';

Console.Write("Student Gender: ");
Console.WriteLine(Gender);
}
}
This would produce:

Student Gender: M
Escape Sequences



An escape sequence is a special character that displays non-visibly. For example, you can use this type of character to indicate the end of line, that is, to ask the program to continue on the next line. An escape sequence is represented by a backslash character, \, followed by another character or symbol. For example, the escape sequence that moves to the next line is \n.

An escape can be included in single-quotes as in '\n'. It can also be provided in double-quotes as "\n".

The C# language recognizes other escape sequences.

Escape Sequence Name Description
\a Bell (alert) Makes a sound from the computer
\b Backspace Takes the cursor back
\t Horizontal Tab Takes the cursor to the next tab stop
\n New line Takes the cursor to the beginning of the next line
\v Vertical Tab Performs a vertical tab
\f Form feed
\r Carriage return Causes a carriage return
\" Double Quote Displays a quotation mark (")
\' Apostrophe Displays an apostrophe (')
\? Question mark Displays a question mark
\\ Backslash Displays a backslash (\)
\0 Null Displays a null character


To use an escape sequence, you can also first declare a char variable and initialize it with the desired escape sequence in single-quotes.

The Byte Data Type



A byte is an unsigned number whose value can range from 0 to 255 and therefore can be stored in one byte. You can use it when you know a variable would hold a relatively small value such as people's age, the number of children of one mother, etc. To declare a variable that would hold a small natural number, use the byte keyword. Here is an example:

byte Age;
You can initialize a byte variable when declaring it or afterwards. Here is an example that uses the byte data type:

using System;

class ObjectName
{
static void Main()
{
Byte Age = 14;
Console.Write("Student Age: ");
Console.WriteLine(Age);

Age = 12;
Console.Write("Student Age: ");
Console.WriteLine(Age);
}
}
Make sure you do not use a value that is higher than 255 for a byte variable, you would receive an error. When in doubt, or when you think that there is a possibility a variable would hold a bigger value, don't use the byte data type as it doesn't like exceeding the 255 value limit.

Practical Learning: Using Bytes



Change the Program.cs file as follows:
using System;

class Program
{
static void Main()
{
byte shirts;
byte pants;

shirts = 4;
pants = 1;

Console.WriteLine("-/- Georgetown Cleaning Services -/-");
Console.WriteLine("========================");
Console.WriteLine("Item Type Qty");
Console.WriteLine("------------------------");
Console.Write("Shirts ");
Console.WriteLine(shirts);
Console.Write("Pants ");
Console.WriteLine(pants);
Console.WriteLine("========================");
Console.WriteLine();
}
}


Execute the program. This would produce:
-/- Georgetown Cleaning Services -/-
========================
Item Type Qty
------------------------
Shirts 4
Pants 1
========================


Close the DOS window
Signed Byte



A byte number is referred to as signed if it can hold a negative of a positive value that ranges from -128 to 127, which can therefore fit in a byte. To declare a variable for that kind of value, use the sbyte keyword. Here is an example:

using System;

class NumericRepresentation
{
static void Main()
{
sbyte RoomTemperature = -88;

Console.Write("When we entered, the room temperature was ");
Console.WriteLine(RoomTemperature);
Console.WriteLine();
}
}
This would produce:

When we entered, the room temperature was -88



--------------------------------------------------------------------------------

Thursday, September 20, 2007

Learn C# by practicals Part 3

Using Variables: Representing Numbers


A Bit


The computer (or an Intel computer, or a computer that runs on an Intel microprocessor) uses the binary system to represent its information. It represents data using only a 0 or 1 value:


0 1

You can represent a piece of information with one of two states. This technique of representing values is the same as the binary system. In the computer, it uses values 0 and/or 1, which themselves are called digits.

The entity used to represent such a value is called a binary digit; in its abbreviated form, it is called a bit (for binary digit). The bit (binary digit) is the most fundamental representation of the computer's counting system.

Although the C# compiler recognizes a bit, you cannot store a variable in a bit. However, eventually, you will be able to manipulate the information stored in a bit.

The Four-Bit Combination



The single bit is used only to represent a tinny piece of information. To get effective numbers, the computer combines the bits. The first combination of bits consists of grouping four consecutive bits.



To count the bits, we number them starting at 0, followed by 1, 2, and 3. The count starts with the most right bit:



The first bit, on the right side of the group, is called the Low Order bit or LO bit. This is also called the least significant bit. The last bit, on the left side of the group, is called the High Order bit or HI bit; it is also called the most significant bit. The bit on the right side is counted as bit 0. The bit on the left side is counted as bit 3. The other bits are called by their positions: bit 1 and bit 2.

Once again, each bit can have one of two states. Continuing with our illustration, when a cup is empty, it receives a value of 0. Otherwise, it has a value of 1. On a group of four consecutive bits, we can have the following combinations:









This produces the following binary combinations: 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111 = 16 combinations. When using the decimal system, these combinations can be represented as 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15.

This combination is also a system that the computer uses to count bits internally. Sometimes, in your program or in the help files, you will encounter a number that is less than four bits, such as 10 or 01 or 101. The technique used to complete and fill out the group of 4 bits consists of displaying 0 for each non-represented bit. The binary number 10 will be the same as 0010. The number 01 is the same as 0001. The number 101 is the same as 0101. This technique is valuable and allows you to always identify a binary number as a divider of 4.

When all bits of a group of 4 are 0, the combination has the lowest value, which is 0000. Any of the other combinations has at least one 0 bit, except for the last one. When all bits are 1, this provides the highest value possible for a group of 4 bits. The lowest value, also considered the minimum value, can be represented in the decimal system as 0. The highest value, also considered the maximum, can be expressed in decimal value as 24 (2 represents the fact that there are two possible states: 0 and 1; 4 represents the fact that there are four possible combinations), which is 16. This produces 16 because 24 = 16.

As you can see, the binary system can appear difficult to read when a value combines various bit representations. To make it easier, the computer recognizes the hexadecimal representation of bits. Following the box combinations above, we can represent each 4-bit of the sixteen combinations using the decimal, hexadecimal, and binary systems as follows:

Decimal Binary Hexadecimal
0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
10 1010 A
11 1011 B
12 1100 C
13 1101 D
14 1110 E
15 1111 F

Table of Numeric Conversions


When looking at a binary value represented by 4 bits, you can get its decimal or hexadecimal values by referring to the table above. A group of four consecutive bits has a minimum and maximum values on each system as follows:

Decimal Hexadecimal Binary
Minimum 0 0x0 0000
Maximum 15 0xf 1111


Although the C# compiler recognizes a group of four consecutive bits, you cannot store any variable in it. You can, however, manipulate the bits of the group.

Monday, September 17, 2007

Learn C# by Practicals Part 2

Introduction to Variables:
The Numeric Systems
When a computer boots, it “loads” the operating system. If you want to use a program, you must find it either on the Start menu or from its directory and take the necessary action to open it. Such a program uses numbers, characters, meaningful words, pictures, graphics, etc, that are part of the program. As these things are numerous, so is the size of the program, and so is the length of time needed to come up. Your job as a programmer is to create such programs and make them available to the computer, then to people who want to interact with the machine.

To write your programs, you will be using alphabetic letters that are a, b, c, d, e, f, g, h, I, j, k, l, m, n, o, p, q, r, s, t, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z. You will also use numeric symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Additionally, you will use characters that are not easily readable but are part of the common language; they are ` ~ ! @ # $ % ^ & * ( ) _ + - = : “ < > ; ‘ , . /. Some of these symbols are used in the C# language while some others are not. When creating your programs, you will be combining letters and/or symbols to create English words or language instructions.

Some of the instructions you will give to the computer could consist of counting the number of oranges, converting water to soup, or making sure that a date occurs after January 15. After typing an instruction, the compiler would translate it to machine language. The computer represents any of your instructions as a group of numbers. Even if you ask the computer to use an orange, it would translate it into a set of numbers. As you give more instructions or create more words, the computer stores them in its memory using a certain amount of space for each instruction or each item you use.


There are three numeric systems that will be involved in your programs, with or without your intervention.

The Binary System



When dealing with assignments, the computer considers a piece of information to be true or to be false. To evaluate such a piece, it uses two symbols: 0 and 1. When a piece of information is true, the computer gives it a value of 1; otherwise, its value is 0. Therefore, the system that the computer recognizes and uses is made of two symbols: 0 and 1. As the information in your computer is greater than a simple piece, the computer combines 0s and 1s to produce all sorts of numbers. Examples of such numbers are 1, 100, 1011, or 1101111011. Therefore, because this technique uses only two symbols, it is called the binary system.

When reading a binary number such as 1101, you should not pronounce "One Thousand One Hundred And 1", because such a reading is not accurate. Instead, you should pronounce 1 as One and 0 as zero or o. 1101 should be pronounced One One Zero One, or One One o One.

The sequence of the symbols of the binary system depends on the number that needs to be represented.

The Decimal System



The numeric system that we are familiar with uses ten symbols that are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Each of these symbols is called a digit. Using a combination of these digits, you can display numeric values of any kind, such as 240, 3826 or 234523. This system of representing numeric values is called the decimal system because it is based on 10 digits.

When a number starts with 0, a calculator or a computer ignores the 0. Consequently, 0248 is the same as 248; 030426 is the same as 30426. From now on, we will represent a numeric value in the decimal system without starting with 0: this will reduce, if not eliminate, any confusion.

Decimal Values: 3849, 279, 917293, 39473
Non- Decimal Values: 0237, 0276382, k2783, R3273

The decimal system is said to use a base 10. This allows you to recognize and be able to read any number. The system works in increments of 0, 10, 100, 1000, 10000, and up. In the decimal system, 0 is 0*100 (= 0*1, which is 0); 1 is 1*100 (=1*1, which is 1); 2 is 2*100 (=2*1, which is 2), and 9 is 9*100 (= 9*1, which is 9). Between 10 and 99, a number is represented by left-digit * 101 + right-digit * 100. For example, 32 = 3*101 + 2*100 = 3*10 + 2*1 = 30 + 2 = 32. In the same way, 85 = 8*101 + 5*100 = 8*10 + 5*1 = 80 + 5 = 85. Using the same logic, you can get any number in the decimal system. Examples are:

2751 = 2*103 + 7*102 + 5*101 + 1*100 = 2*1000 + 7*100 + 5*10 + 1 = 2000 + 700 + 50 + 1 = 2751

67048 = 6*104 + 7*103 + 0*102 + 4*101 + 8*100 = 6*10000 + 7*1000+0*100+4*10+8*1 = 67048

Another way you can represent this is by using the following table:

etc Add 0 to the preceding value 1000000 100000 10000 1000 100 10 0

When these numbers get large, they become difficult to read; an example is 279174394327. To make this easier to read, you can separate each thousand fraction with a comma. Our number would become 279,174,394,327. You can do this only on paper, never in a program: the compiler would not understand the comma(s).

The Hexadecimal System



While the decimal system uses 10 digits (they are all numeric), the hexadecimal system uses sixteen (16) symbols to represent a number. Since the family of Latin languages consists of only 10 digits, we cannot make up new ones. To compensate for this, the hexadecimal system uses alphabetic characters. After counting from 0 to 9, the system uses letters until it gets 16 different values. The letters used are a, b, c, d, e, and f, or their uppercase equivalents A, B, C, D, E, and F. The hexadecimal system counts as follows: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, and f; or 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. To produce a hexadecimal number, you use a combination of these sixteen symbols.

Examples of hexadecimal numbers are 293, 0, df, a37, c23b34, or ffed54. At first glance, the decimal representation of 8024 and the hexadecimal representation of 8024 are the same. Also, when you see fed, is it a name of a federal agency or a hexadecimal number? Does CAB represent a taxi, a social organization, or a hexadecimal number?

From now on, to express the difference between a decimal number and a hexadecimal one, each hexadecimal number will start with 0x or 0X. The number will be followed by a valid hexadecimal combination. The letter can be in uppercase or lowercase.
Legal Hexadecimals: 0x273, 0xfeaa, 0Xfe3, 0x35FD, 0x32F4e
Non-Hex Numbers: 0686, ffekj, 87fe6y, 312


There is also the octal system but we will not use it anywhere in our applications.

Signed and unsigned



The numbers we have used so far were counting from 0, then 1, then 2, and up to any number desired, in incrementing values. Such a number that increments from 0, 1, 2, and up is qualified as positive. By convention, you do not need to let the computer or someone else know that such a number is positive: by just displaying or saying it, the number is considered positive. This is the basis of our counting items.

In real life, there are numbers counted in decrement values. Such numbers start at –1 and move down to -2, -3, -4 etc. These numbers are qualified as negative.

When you write a number “normally”, such as 42, 502, or 1250, the number is positive. If you want to express the number as negative, you use the – on the left side of the number. The – symbol is called a sign. Therefore, if the number does not have the – symbol, C++ (or the compiler) considers such a number as unsigned. In C++, if you declare a variable that would represent a numeric value and you do not initialize (assign a value to) such a variable, the compiler will consider that the variable can hold either a signed or an unsigned value. If you want to let the compiler know that the variable should hold only a positive value, you will declare such a variable as unsigned.

Data Types



In order to use a variable in your program, the compiler must be aware of it. Once the compiler knows about a variable, it would reserve an amount of memory space for that variable


Using its name, you can refer to a particular variable when necessary. Because there are various types of variables a program can use, such as the employee's name, the residence, the desired salary, years of experience, education level, etc for our employment application analogy, the compiler needs a second piece of information for each variable you intend to use. This piece of information specifies the amount of space that a variable needs. You can see that, to store a character, such as an employee's gender (M or F) or an answer as Y or N to a question, the compiler would certainly not need the same amount of space to store the name of the last school attended by an employee.

A data type is an amount of space needed to store the information related to a particular variable.

The name of a variable allows you and the compiler to refer to a particular category of information in your program. The data type allows the compiler to reserve an adequate amount of memory space for a variable. Because you are the one who writes a program, you also tell the compiler the amount of memory space each particular variable will need. Based on this, the C# language provides categories of data types used to specify this amount of space needed for a variable.,/p>

As stated already, before using a variable, you must communicate your intentions to the compiler. Making the compiler aware is referred to as declaring the variable. To declare a variable, provide the data type followed by the name of the variable. Therefore, the syntax used to declare a variable is:

DataType VariableName;
In the next lesson, we will review the assignment operator. For now, we will know that we can use it to provide a new value to a variable. The assignment operator is represented by =.

Saturday, September 15, 2007

Learn C# by examples part 1

C# (pronounced "C Sharp") is a language used to create computer applications that tell the machine what to do and when. In the various lessons on this web site, we study the C# language by creating console applications, which are text-based programs that display their results in a black or gray window.

C#, pronounced c sharp, is a computer language used to give instructions that tell the computer what to do, how to do it, and when to do it. This is a universal language that is used on many operating systems, including Microsoft Windows. C# is one of the languages used in the Microsoft .NET Framework. The Microsoft .NET Framework is a library of objects that create or draw things on the computer.

Console Applications



The C# language is used to create applications that display on a black window referred to as the DOS prompt or DOS window. Those are the types of applications we will learn to create in our lessons.

To study the C# language, we will use Microsoft Visual C# 2005 Express Edition or Microsoft Visual C# 2005 Professional (or any other version you have). To get it, you can download it free from the Microsoft web site. After downloading it, you can open it by clicking Start -> (All) Programs -> Microsoft Visual C# 2005 Expression Edition:



To create the type of applications we will study in our lessons, on the main menu, you can click File -> New Project... In the Templates section of the New Project dialog box, you can click Console Application, accept the default name or change it:



After clicking OK, a skeleton code would be created for you. Right now, we will not review what ever is part of the code. Everything will be introduced and explained as we move on.


Introduction to Variables


Definition


A computer receives information from different applications in various forms. Sometimes a person types it using the keyboard. Sometimes the user clicks the mouse. Sometimes information comes from another, more complicated source. The idea is that the computer spends a great deal of its time with various pieces of information. Information provided to the computer through a program is called datum and the plural is data. Sometimes the word data is used both for singular and plural items.

Data used by the computer comes and goes regularly as this information changes. For this reason, such information is called a variable.

When the user enters data in a program, the computer receives it and must store it somewhere to eventually make it available to the program as needed. For a program used to process employment applications, the types of information a user would enter into the program are the name, the residence, the desired salary, years of experience, education level, etc. Because there can be so much information for the same program, you must specify to the computer what information you are referring to and when. To do this, each category of piece of information must have a name.

Practical Learning: Introducing Variables



Microsoft Visual C# 2005 Express Edition or Microsoft Visual C# 2005 Professional
From now on, we will only refer to Microsoft Visual C#

To create a new application, on the Start Page, on the right side of Create, click Project
In the Templates section, click Console Application
Change the Name to GeorgetownCleaningServices2 and click OK
Names in C#



To name the variables of your program, you must follow strict rules. In fact, everything else in your program must have a name. C# uses a series of words, called keywords, for its internal use. This means that you must avoid naming your objects using one of these keywords. They are:

abstract const extern int out short typeof
as continue false interface override sizeof uint
base decimal finally internal params stackalloc ulong
bool default fixed is private static unchecked
break delegate float lock protected string unsafe
byte do for long public struct ushort
case double foreach namespace readonly switch using
catch else goto new ref this virtual
char enum if null return throw void
checked event implicit object sbyte true volatile
class explicit in operator sealed try while

Besides these keywords, C# has other words that should be reserved only depending on how and where they are used. These are referred to as contextual keywords and they are:

get partial set value where yield

Once you avoid these words, there are rules you must follow when naming your objects. On this site, here are the rules we will follow:

The name must start with a letter or an underscore
After the first letter or underscore, the name can have letters, digits, and/or underscores
The name must not have any special characters other than the underscore
The name cannot have a space
Besides these rules, you can also create your own but that abide by the above.

C# is case-sensitive. This means that the names Case, case, and CASE are completely different. For example, main is always written Main.

Values and Variables on the Console



As mentioned already, the applications we will create display in a dark object called the DOS window. Here is an example showing some values:



To display a value in this window, you can enter it in the parentheses of the Console.Write() or Console.WriteLine(). Here are two examples:

using System;

class Program
{
static void Main()
{
Console.WriteLine(248);
Console.Write(1);
}
}
If you write Console.WriteLine() with empty parentheses, an empty line would be displayed. In future lessons, we will learn what the meanings of Console, Write(), and WriteLine().

Thursday, September 13, 2007

ABAP Source Code Enhancements

Use
As part of the enhancement concept, it is possible to enhance ABAP source code, without modifications, using source code plug-ins.

You can execute enhancements to implicit and explicit enhancement options. The Enhancement Builder tool for defining explicit enhancement options and for implementing enhancements is integrated in the ABAP Editor.



In the nomenclature of the enhancement concept, an enhancement option represents (in an ABAP source code) both the enhancement spot element definition, and the enhancement spot element call. A source code plug-in, however, refers to an enhancement implementation element of a (simple) enhancement implementation.

Source Code Plug-in Technology
Although source code plug-ins are displayed in the same source code as the respective enhancement options, the plug-ins are actually stored in other include programs managed by the Enhancement Builder:
The following enhancement option types are available in a source code:

· ENHANCEMENT-POINT – can either be static (for example, additional data declaration) or dynamic (for example, additional coding).

· ENHANCEMENT-SECTION – can either be static (for example, replace an existing data declaration) or dynamic (for example, replace coding).

· Overlay enhancement – overwrite an existing enhancement instead of modifying it.

Enhancement options and sections are hooks to which you can assign an enhancement. That is, you can enhance an option by an enhancement.



Data declarations are always static, even if they are inside a dynamic enhancement option.

Form routines, methods, and local classes cannot be part of dynamic enhancement options/sections. Therefore, it is necessary to place them into static enhancement options/sections.

Static enhancement options/sections are marked with STATIC in coding. Dynamic enhancement options/sections do not contain an addition.

Source Code Enhancements vs. Modifications
Advantages of source code enhancements:

· no modifications;

· no object key is needed;

· are switchable by the switch framework;

· fewer upgrade effort.

Disadvantages of source code enhancements:

· exist only at special source code lines (implicit, explicit).



Use
In ABAP programs, implicit enhancement options are predefined at the following places:

· At the end of an include. There are some restrictions, for example, not at the end of a method include.

· At the end of a PUBLIC-, PROTECTED-, PRIVATE-SECTION of a class.

· At the end of the implementation part of a class (before the ENDCLASS, which belongs to CLASS … IMPLEMENTATION).

· At the end of an interface definition (before the ENDINTERFACE).

· At the end of a structure definition (before TYPES END OF, DATA END OF, CONSTANTS END OF, and STATICS END OF).

· At the beginning and at the end of a procedure (FORM, FUNCTION, METHOD). That is, after commands FORM, FUNCTION, and METHOD, and before statements ENDFORM, ENDFUNCTION, and ENDMETHOD.

· At the end of the CHANGING-, IMPORTING-, EXPORTING-parameter list of a method. These enhancement options are located in the middle of a statement.



Implicit enhancement options always exist and no enhancement spot is assigned to them.

Use
In ABAP programs, you can select either a position or a program section as an explicit enhancement option. Source code plug-ins for an enhancement are either entered at such a position or they replace the selected section.



An explicit enhancement option of an ABAP program is part of the program. It is thus assigned to the package of the program and not necessarily to the package of the enhancement spot to which it belongs.

Activities
· To mark a position in an ABAP program as an explicit enhancement option, use the following ABAP statement:

ENHANCEMENT-POINT enh_id SPOTS spot1 spot2 ...

· To mark a section in an ABAP program as an explicit enhancement option, use the following ABAP statement:

ENHANCEMENT-SECTION enh_id SPOTS spot1 spot2 ...
...
END-ENHANCEMENT-SECTION.

Using enh_id, you define the name of the enhancement option or the source code enhancement. After SPOTS, the enhancement option must be assigned to at least one (simple) enhancement spot. For a detailed description of the statements, refer to the ABAP keyword documentation.

An enhancement spot for source code enhancements is created using forward navigation from within the ABAP Editor. The statements can either be entered directly or generated by selecting Enhancements ® Create Enhancement.

After the program has been saved, the enhancement option is managed by the Enhancement Builder, and can only be deleted using the function Enhancements ® Remove Enhancement.

During program generation, the source code plug-ins that are in the current system for the assigned enhancement implementations and have the switch status stand-by or on, are included at this position or they replace the selected section.

Monday, September 10, 2007

Coding Cokkie Part 2

Baking a Cookie with Multiple Values
The previous two examples have used a single variable. Now you can try creating a cookie file that stores multiple values:

Start with the HTML template.
< HTML>
< HEAD>
< TITLE>Setting a cookie [3]< /TITLE>
< SCRIPT LANGUAGE="vbscript">

< /SCRIPT>
< BODY BGCOLOR="white">
< CENTER>
< INPUT TYPE="button" NAME="cmdButton1" VALUE="Get Cookie Value">
< /CENTER>
< /BODY>
< /HTML>

Add the following code between the < SCRIPT > tags:
1: Dim VarName
2: Dim VarVal
3: Dim VarName1
4: Dim VarVal1
5: Dim Exp
6:
7: Exp = "expires=Wednesday, 09-Nov-1999 23:12:40 GMT"
8: VarName = "mycookie"
9: VarVal = Date()
10: VarName1 = "nextname"
11: VarVal1 = "anything;"
12:
13: Document.Cookie = VarName & "=" & VarVal & ";"
& VarName1 & "=" & VarVal1 & Exp


Notice that in this example the semicolon that delimits the second value is attached to the string as part of the second value.
Again, add the event handler for the button, which displays the two
name/value pairs as shown in Figure 19.4.
Figure 19.4 : The two name/value pairs are now displayed.

Sub cmdButton1_OnClick
Alert Document.Cookie
End Sub

Here's the complete code for the multiple value example. You can add as many name/value pairs as you require, up to a maximum total cookie size of 4KB.

< HTML>
< HEAD>
< TITLE>Setting a cookie [3]< /TITLE>
< SCRIPT LANGUAGE="vbscript">
Dim VarName
Dim VarVal
Dim VarName1
Dim VarVal1
Dim Exp

Exp = "expires=Wednesday, 09-Nov-1999 23:12:40 GMT"
VarName = "mycookie"
VarVal = Date()
VarName1 = "nextname"
VarVal1 = "anything;"

Document.Cookie = VarName & "=" & VarVal & ";" & VarName1 & "=" & VarVal1 & Exp

Sub cmdButton1_OnClick
Alert Document.Cookie
End Sub

< /SCRIPT>
< BODY BGCOLOR="white">
< CENTER>
< INPUT TYPE="button" NAME="cmdButton1" VALUE="Get Cookie Value">
< /CENTER>
< /BODY>
< /HTML>



Reading Individual Cookie Values
In the real world, you need to get hold of individual cookie values rather than the complete cookie or a name/value pair. This requires you to get involved in manipulating the string that is returned by Document.Cookie.

The string that is returned is the complete cookie-basically, a series of name/value pairs delimited by semicolons. Therefore, you need to find the variable name within the string, and from its position in the string, you can then extract the value associated with that variable. This example shows you how to dissect the cookie string in order to return the value of a specific variable within the cookie.

The HTML template for this example is slightly different from the ones used before. For ease of demonstration, each of the two variables within the cookie will be returned by clicking on the appropriate button.

< HTML>
< HEAD>
< TITLE>Getting a Cookie< /TITLE>
< SCRIPT LANGUAGE="vbscript">

< /SCRIPT>
< BODY BGCOLOR="white">
< CENTER>
< INPUT TYPE="button" NAME="cmdButton1" VALUE="Get MyCookie Value">
< P>
< INPUT TYPE="button" NAME="cmdButton2" VALUE="Get NextName Value">
< /CENTER>
< /BODY>
< /HTML>

When you've entered the HTML template, between the < SCRIPT > tags add the following two event handlers for the two buttons. Note that each one calls the same custom procedure, passing the name of the variable to be returned.

Sub cmdButton1_OnClick
Call GetCookieValue("mycookie")
End Sub

Sub cmdButton2_OnClick
Call GetCookieValue("nextname")
End Sub

Now you can enter the custom procedure. Again, the line numbers are only for ease of explanation.

1: Sub GetCookieValue(CkName)
2:
3: CkNameLen = Len(CkName)
4:
5: If InStr(Document.Cookie, CkName) = 0 Then
6: Alert "Cookie value not found"
7: Else
8: CkValStart = InStr(Document.Cookie, CkName) + CkNameLen + 1
9:
10: If InStr(CkValStart, Document.Cookie, ";") = 0 Then
11: CkVal = Mid(Document.Cookie, CkValStart)
12: Else
13: CkValEnd = InStr(CkValStart, Document.Cookie, ";")
14: CkValLen = CkValEnd - CkValStart
15: CkVal = Mid(Document.Cookie, CkValStart, CkValLen)
16: End If
17:
18: Alert CkVal
19: End If
20: End Sub

The custom procedure prototype is on line 1, and it requires that the name of the cookie variable be passed into the procedure when it is called. The length of the name string is obtained and assigned to the variable CkNameLen in line 3.

Line 5 checks to make sure that the variable name is present within the cookie string. If it is not, a warning message is displayed and the procedure is terminated.

If the variable name is found within the cookie string, execution continues at line 8, where the position of the first character of the variable value is calculated. This is done by adding the length of the variable name to the start position of the variable name to give the end position of the variable name. Then you add one further character to basically jump past the = that sits between the variable name and the variable value.

If the variable value that you are seeking is the last one in the cookie, the semicolon will not appear after the value. Therefore, line 10 checks to see whether a semicolon is present at some point after the start of the variable value. If not, this is the last value of the cookie, and its end point can be taken as the end point of the overall cookie. If there is a semicolon present after the variable value, the position of the semicolon is the end point of the variable value.

The Mid function used in line 11 does not use a string length element and, therefore, Mid returns a string that ends at the last character of the source string. The Mid function in line 15 uses the calculated length of the value string to pluck the value from the source string.

Here's the complete source code for the example. The results of clicking the two buttons are shown in Figures 19.5 and 19.6.

Figure 19.5 : Click the MyCookie button to return the value of the mycookie variable.

Figure 19.6 : Click the NextName button to return the value of the nextname variable.

< HTML>
< HEAD>
< TITLE>Getting a Cookie< /TITLE>
< SCRIPT LANGUAGE="vbscript">

Sub cmdButton1_OnClick
Call GetCookieValue("mycookie")
End Sub

Sub cmdButton2_OnClick
Call GetCookieValue("nextname")
End Sub

Sub GetCookieValue(CkName)

CkNameLen = Len(CkName)

If InStr(Document.Cookie, CkName) = 0 Then
Alert "Cookie value not found"
Else
CkValStart = InStr(Document.Cookie, CkName) + CkNameLen + 1

If InStr(CkValStart, Document.Cookie, ";") = 0 Then
CkVal = Mid(Document.Cookie, CkValStart)
Else
CkValEnd = InStr(CkValStart, Document.Cookie, ";")
CkValLen = CkValEnd - CkValStart
CkVal = Mid(Document.Cookie, CkValStart, CkValLen)
End If

Alert CkVal
End If
End Sub

< / SCRIPT>
< BODY BGCOLOR="white">
< CENTER>
< INPUT TYPE="button" NAME="cmdButton1" VALUE="Get MyCookie Value">
< P>
< INPUT TYPE="button" NAME="cmdButton2" VALUE="Get NextName Value">
< / CENTER >
< / BODY >
< / HTML >

Thursday, September 6, 2007

Cookies with VBScript Part 1

So what is a cookie? A cookie is a simple text file that is linked to a particular Web document and is stored on the client machine. "Ah," I can hear you say, "but VBScript doesn't allow you to read and write files on the client machine." In the general sense this is true, but cookies are not ordinary files.

A cookie file is a very limited ASCII text; therefore, it cannot contain any potentially harmful binary code. Furthermore, the only way that it can be written to or read from the Web is by the page that originally created it. To see the cookie files you've already collected on your travels around the Web, open your Windows Explorer and open the Cookies subdirectory within the Windows directory.

Security Issues
When cookies were first introduced, some people thought-and some still do-that the humble cookie would be a security risk. So first of all, let me put your mind at ease. Cookies cannot read information from your hard drive, nor can they publicize your personal information to the world. Here's a list of the limitations placed on cookies:

A client machine cannot store more than 300 cookies.
A client machine cannot store more than 20 cookies from a single domain.
Only cookies that have an expiration date associated with them are stored on the client machine. Most cookies are simply lost when the browser is exited.
A cookie is not a program. It is simply an ASCII text file.
Cookies cannot obtain personal information, unless you have given that information to the domain associated with the cookie (for example, in a questionnaire).
A cookie can be read only by the domain that created it.
What Can You Use Cookies For?
Cookies have allowed the creation of a range of new applications, including shopping carts. This is because cookies store variables that can be used from page to page, or written and read every time a user enters a Web site. Here are just a few examples of how you could use cookies:

Maintain a list of selected items, quantities, and colors in a shopping application.
Maintain a record of the number of times a user has visited your site.
Store the date that a user last visited your Web site, and highlight items that have changed since his last visit.
Maintain a user-customized color scheme for your Web site.
Maintain a basic information file for a user-that is, first name, preferences, and so on-to enable you to personalize the site for the user.
Cookie Variables
Cookie values are stored as name=value pairs, delimited with a semicolon (;). You can create your own variable names and assign values to them, and you can set several standard cookie variables.

domain
syntax: domain=domain_name;

When the client searches the list of cookie files, a comparison of the domain name attributes of the cookie file is made with the domain name of the host from which the Web page has been fetched. If the domain name minus the machine name (such as mcp.com) matches the stored domain name-which is known as tail matching-the cookie then performs path matching.

Only hosts within the specified domain can set a cookie for that domain, and domains must have at least two or three periods in them to prevent generic domains such as .com or .net. The default value of domain is the host name of the server that initially generated the cookie file.

path
syntax: path=path;

The path attribute is used to specify the URLs within a domain for which the particular cookie is valid. When the domain matching has been successfully completed, the pathname component of the URL is compared with the path attribute. The path
/laura would match /lauralemay and /laura/lemay.html. If a path attribute is not specified, the path is assumed to be that of the document calling the cookie.

secure
syntax: secure;

The secure attribute specifies that the cookie can be transmitted only if the communications channel with the host is a secure one. If secure is not specified, a cookie is considered safe to be sent openly, or "in the clear," over unsecured channels. However, you are dealing with client-side scripting, so the secure attribute is somewhat redundant because your VBScript cookies are never "transmitted" and remain within the client environment.

Expiration Date
syntax: expires=date;

The expiration date attribute must be written in a particular format to be recognized.

day, dd-mmm-yy hh:mm:ss GMT

Here is an example:

Thursday, 09-Oct-97 15:01:00 GMT

This poses something of a problem in VBScript, because you don't have access to a GMT date format, like you would in JavaScript. A work-around to this is to hard code an expiration date that is far into the future, say 1999. Otherwise, you will have to resort to mixing JavaScript in your document to calculate the current time offset to GMT at the client.



Baking a Temporary Cookie
A temporary cookie is one that exists only while the browser is open; when the browser is closed, the cookie is gone. This first example demonstrates how to set the value within a temporary cookie and then read back the name/value pair.

Start by entering the following HTML into Notepad or your usual HTML editor:


Setting a cookie [1]
< SCRIPT LANGUAGE="vbscript" >

< / SCRIPT >


< IN PUT TYPE="button" NAME="cmdButton1" VALUE="Show Cookie Value" >




Now you need to add the VBScript code that writes the cookie value when the page is loaded. The following code goes between the
Time is
My Photo
Name: saba wasim
Location: DeLhI, dElHi, India

ƒυη-ℓσνιηg αη∂ α∂νєηтυяσυѕ ρєяѕση, ωнσ ιѕ ƒαмιℓу-σяιєηтє∂ αη∂ мσтιναтє∂ тσ ℓινє ℓιƒє тσ ιтѕ ƒυℓℓєѕт αη∂ тσ ѕнαяє ιт ωιтн ѕσмєσηє.α νιѕισηαяу ℓєα∂єя—ѕтяσηg, ѕєℓƒ-яєℓιαηт, αη∂ ∂яινєη тσ мαкє αη ιмρα¢т. ρєσρℓє ∂єѕ¢яιвє нιм αѕ α ¢συяαgєσυѕ, "ƒσя¢є тσ вє яє¢кσηє∂ ωιтн," υηαƒяαι∂ σƒ яιѕк σя мαкιηg υηρσρυℓαя ∂є¢ιѕισηѕ. αѕ α ƒяιєη∂, нє'ѕ ƒιєя¢єℓу ℓσуαℓ αη∂ тняινєѕ ση ѕтιмυℓαтιηg ¢σηνєяѕαтιση αη∂ ѕнαяιηg














































FOR SPENDING TIME
MORE TO COME


Blog Design By: Sam hacker Corp.

Top Computers blogs

eXTReMe Tracker