Programming Notes

 

22 September 2007

 

Contents

1      AWK.. 7

2      C.. 8

2.1       Environment Variables. 8

2.2       switch.. 8

2.3       True and False. 8

3      Character Sets. 9

3.1       charmap. 9

3.2       gettext (GNU) 9

4      Expect.. 9

4.1       Arguments. 9

4.2       Comments. 10

4.3       Debugging.. 10

4.4       Regular Expressions. 10

4.5       Strings with leading hyphens misinterpreted as flags. 11

4.6       timeout. 11

5      Java and ActiveX.. 12

6      JavaScript (Netscape) and JScript (Microsoft) 12

6.1       Overview... 12

6.1.1        Why Use JavaScript?. 12

6.1.2        History. 12

6.1.3        References. 13

6.1.4        Capabilities. 13

6.1.5        Limitations. 14

6.1.6        Versions. 14

6.2       DOM (Document Object Model) 14

6.2.1        Specifying a leaf node. 15

6.2.2        Properties and Methods of Common Objects. 16

6.3       Embedding.. 16

6.3.1        script tag. 16

6.3.2        Attribute/Value pair in a tag. 17

6.3.3        Sourcing Code Files. 17

6.4       Comments. 18

6.5       Operators. 18

6.5.1        Unary. 18

6.5.2        Binary. 18

6.5.3        Ternary. 19

6.6       Variables. 19

6.6.1        Names. 19

6.6.2        Declaration. 19

6.6.3        Dereferencing. 19

6.6.4        Data Types. 19

6.6.5        Scope. 20

6.7       Statements. 20

6.8       Special Characters. 20

6.9       Control Flow... 21

6.9.1        if 21

6.9.2        switch. 21

6.9.3        loops. 22

6.10     Functions/Methods. 24

6.10.1      Built-in. 24

6.10.2      Definition. 24

6.10.3      Execution. 25

6.11     Objects. 25

6.11.1      Object Properties. 25

6.11.2      Objects as Associative Arrays. 25

6.11.3      Object Types. 26

6.12     Internet Explorer Scripting Object Model. 30

6.12.1      The Window Object 30

6.12.2      The Document Object 31

6.12.3      The Form Object 33

6.13     Navigator Built-In Objects. 34

6.13.1      navigator. 34

6.13.2      window.. 35

6.13.3      location. 35

6.13.4      history. 36

6.13.5      document 37

6.13.6      form.. 38

6.13.7      date. 39

6.13.8      string. 40

6.13.9      math. 41

6.14     Global functions not associated with objects. 42

6.15     Events and Event Handlers. 43

6.15.1      onClick Syntax. 44

6.15.2      onSubmit Syntax. 44

6.15.3      onReset Syntax. 45

6.15.4      onChange Syntax. 45

6.15.5      onLoad Syntax. 46

6.15.6      onUnload Syntax. 46

6.15.7      onMouseOver Syntax. 46

6.16     Intrinsic HTML Controls. 47

6.16.1      Button. 47

6.16.2      Checkbox. 48

6.16.3      Hidden. 48

6.16.4      Password. 49

6.16.5      Radio. 50

6.16.6      Reset 50

6.16.7      Select 51

6.16.8      Submit 52

6.16.9      Text 52

6.16.10        Textarea. 53

6.17     Message Boxes (user I/O) 54

6.17.1      alert() 54

6.17.2      confirm() 54

6.17.3      prompt(message, default) 54

6.18     Forms. 54

6.18.1      Form Field Validation. 56

6.18.2      Radio Buttons. 59

6.19     Drop-Down Lists. 60

6.20     Browser Windows. 63

6.21     Frames. 64

6.22     MouseOver Effects. 67

6.23     Date Objects. 70

6.24     Cookies. 72

6.25     FAQs. 75

6.25.1      SaveAs. 75

6.25.2      How to write text to an MS Excel file. 76

6.25.3      Where to download old browsers like IE4. 76

6.25.4      How can I read a table cell's content?. 76

6.25.5      How do I get the text content of a link?. 78

6.25.6      How can I remove the mark up from an HTML element's content?. 78

6.25.7      How to retrieve the HTML of the file that it's in?. 79

7      Perl.. 81

7.1       Documentation.. 81

7.2       File Extensions. 81

7.3       Modules. 81

7.3.1        Built-in. 81

7.3.2        Bundled. 81

7.3.3        Documentation. 82

7.3.4        Finding and Downloading. 82

7.3.5        Location. 84

7.3.6        Using. 84

7.4       Objects. 85

7.5       Package. 85

7.6       Ports. 85

7.6.1        Palm OS. 85

7.7       Regular Expressions. 85

7.7.1        Greedy vs Minimal Matching. 85

7.8       Scoping.. 85

7.9       Sorting.. 86

7.9.1        Sorting Hashes by Value. 86

7.10     System Interaction.. 86

7.10.1      system() 86

7.11     Switches. 87

7.12     Variables. 87

7.12.1      $/ (input record separator) 87

7.12.2      $. (input record number) 87

7.12.3      @INC.. 87

7.12.4      Tied Variables. 87

7.12.5      Initializing Arrays. 88

8      PHP. 89

8.1       Accessing Remote Web Pages. 89

8.1.1        Snoopy. 89

8.1.2        urlencode. 89

8.1.3        Authentication (Regular) 89

8.1.4        Authentication (Digest) 90

8.2       Command Line Invocation.. 92

8.3       Design.. 92

8.4       Forms. 92

8.4.1        Auto Submit 92

8.5       Functions. 93

8.5.1        Defining a function with no parameters. 93

8.5.2        Arithmetic. 93

8.5.3        String. 93

8.6       MySQL. 93

8.6.1        Persistent Connections. 93

8.7       Object Oriented Programming (OOP) 94

8.7.1        Encapsulation. 95

8.8       Operators. 95

8.8.1        Arithmetic. 95

8.8.2        String. 95

8.9       Regular Expressions. 95

8.9.1        Greedy. 95

8.10     Running Shell Commands. 96

8.10.1      system() 96

8.10.2      exec() 96

8.10.3      passthru() 97

8.11     Sessions. 98

8.12     Strings and Character Sets. 98

8.12.1      Supporting Internationalization (i18n) 99

8.12.2      String access and modification by character. 100

8.12.3      Character Type Functions. 100

8.12.4      gettext (GNU) 101

8.13     Variables. 101

8.13.1      PHP.. 101

9      Shells (UNIX) 103

10        Visual Basic.. 104

10.1     Derivative Languages. 104

11        Visual Basic for Applications. 105

12        Visual Basic Scripting.. 106

12.1     Overview... 106

12.1.1      Description. 106

12.1.2      History. 106

12.1.3      Uses. 106

12.1.4      Functionality. 107

12.2     Documentation.. 107

12.2.1      Tutorials. 107

12.2.2      Microsoft 108

12.3     Comments. 108

12.4     Case Insensitivity.. 108

12.5     Running VBScripts. 108

12.5.1      cscript 109

12.5.2      wscript 109

12.5.3      Setting the Default Script Host 109

12.6     Input and Output. 109

12.7     Procedures. 109

12.7.1      Sub Procedures. 110

12.7.2      Function Procedures. 110

12.7.3      Getting Data into and out of Procedures. 111

12.7.4      Using Sub and Function Procedures in Code. 111

12.8     Operators. 111

12.8.1      String Concatenation (&) 111

12.9     HTML Applications (HTAs) 112

12.10       Q and A.. 112

12.10.1        Sometimes in VBScript I get errors if I don't use parentheses around function arguments and other times I get the error "can't use parentheses when calling a subroutine" when I *do* use them. What's the problem?  112

13        Windows Programming.. 114

13.1     Terms. 114

13.2     Active Directory Service Interfaces (ADSI) 114

13.3     ActiveX.. 114

13.3.1      How to Run a Program in a Script 115

13.4     Active Server Pages. 116

13.5     DirectX.. 116

13.6     DOS Batch.. 116

13.7     Windows Management Instrumentation (WMI) 118

13.8     Windows Scripting Host (WSH) 119

14        UNIX Programming.. 120

14.1     Common cc Compiler Options. 120

14.2     Environment Variables. 120

14.3     Include/Header files. 120

14.4     Libraries. 121

14.4.1      How do I create a static (.a) library? How about a shared (.so) library?. 121

14.5     Make. 122

14.5.1      Rules. 122

14.5.2      Debugging. 122

14.5.3      Command line options. 122

14.5.4      Example makefile. 124

14.6     How to use Imakefiles. 124

14.7     Lint. 125

14.8     Debugging with truss. 125

14.8.1      close() 125

14.8.2      ioctl() 126

14.8.3      mmap() 126

14.8.4      open() 127

14.9     AIX Compilers. 128

15        Compiler Technology.. 129

15.1     Language Generations. 129

15.2     Compilers. 129

15.3     Linkers. 129

15.4     Loaders. 130

 


1         AWK

 

$0 = all positional parameters

 


2         C

 

2.1      Environment Variables

 

set PATH=($path $IMPACT_HOME/bin $SM_HOME/bin $GUI_HOME/bin)

set LD_LIBRARY_PATH=($IMPACT_HOME/platform/solaris2/pgsql/lib $SM_HOME/platform/solaris2/pgsql/lib)

 

2.2      switch

 

Only use ' ' for single characters in a switch statement. Never use them when dealing with integers. Switch statements also cannot deal with strings. For strings use the if statement with the strcmp or stricmp to compare them.

 

2.3      True and False

false = 0

true = non-zero

 


3         Character Sets

 

UTF-8 (Unicode Transmission Format 8)

 

http://www.joelonsoftware.com/articles/Unicode.html

 

http://www.unicode.org/

 

http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&item_id=IWS-Chapter03

 

3.1      charmap

 

Windows app displaying Unicode code points

 

If you know the Unicode equivalent of the character you want to insert, you can also insert a special character directly into a document without using Character Map. To do so, open the document and position the insertion point where you want the special character to appear. Then, with NUM LOCK on, hold down the ALT key while using the number pad keys to type the Unicode character value.

 

3.2      gettext (GNU)

 

http://www.gnu.org/software/gettext/manual/gettext.html

 

4         Expect

 

Traditional Expect is TCL-based.  The Expect Perl module has the same functionality but uses Perl rather than TCL as its language.

 

Official web site: http://expect.nist.gov

Free distribution for Windows from http://ww.activestate.com

 

http://wiki.tcl.tk/201 - documentation links, examples, tutorials

 

4.1      Arguments

 

-- may be used to delimit the end of the options.   This is useful if you want to pass an option-like argument to your script without it being interpreted by  Expect.   This can usefully be placed in the #! line to prevent any flag-like interpretation by Expect.  For example, the following will leave the original arguments (including the script name) in the variable argv.

 

         #!/usr/local/bin/expect --

 

 

The first line of script must have a trailing '--', e.g.:

 

#!/usr/local/bin/expect --

 

4.2      Comments

 

Expect is finicky about how you form comments.  The ';' is required in some circumstances and forbidden in others as the following code fragment illustrates:

 

  expect {

    ">" {                               # saw last page of processes,

      break                             ;#   so we're done

    }

    " --More--" {                       # have another page to view,

      send " "                          ;#   so view it

    }

  }

 

4.3      Debugging

 

The -d flag enables some diagnostic output, which primarily reports internal activity of commands such as expect and interact.  This flag has the same effect as "exp_internal 1" at the beginning of an Expect script, plus the version of Expect is printed.  (The strace command is useful for tracing statements, and the trace command is useful for tracing variable assignments.)  (When using Expectk, this option is specified as -diag.)

 

4.4      Regular Expressions

 

In this example:

 

set prompt "router.(>|#)"

 

the ‘.’ is a wildcard (any single character) and the parens denote single character alternative between ‘>’ and ‘#’.

 

 

Example of expecting a regular expression:

 

  expect {

        -re "\nhostname (.*)\r" {

                set hostname $expect_out(1,string)

                #puts "BUFFER: <$expect_out(buffer)>"

        }

        default {

                puts "hostname not found.  Exiting."

                exit

        }

  }

 

4.5      Strings with leading hyphens misinterpreted as flags

 

Strings like "--More--" get interpreted as an Expect command parameter.  So, change to something like " --More--" or specify the string as an argument to -re as illustrated below:

 

  expect {

        -re "-i9" {

                exit 2                  ;# SMI

        }

        -re "-ipbase" {

                exit 2                  ;# SMI

        }

        -re "-i5" {

                exit 3                  ;# EMI

        }

        -re "-ipservices" {

                exit 3                  ;# EMI

        }

        default {

                exit 4

        }

  }

 

4.6      timeout

 

while {$tries <= $max_tries && $connected == 0}  {

       incr tries

       expect {

          $exp1   {send -s $send1}

          timeout {continue}

          }

       expect {

          ">? "   {send -s "\n"}

          timeout {continue}

          }

       expect {

          $exp2   {incr connected;send -s $send2}

          timeout {continue}

          }

}

 


5         Java and ActiveX

 

Provide animation and dynamic content through interaction between the server and the browser.

 

6         JavaScript (Netscape) and JScript (Microsoft)

 

6.1      Overview

 

Like VBScript, JavaScript executes strictly at the browser level.

 

interpreted, object-based scripting language

runs in ASP (Active Server Pages in IIS), IE, or WSH (Windows Scripting Host)

 

no built-in support for file access

loosely-typed (don’t have to declare data types of variables explicitly)

“literals” = numbers

 

Jscript program = collection of statements

statement = one or more expressions, keywords or operators; a statement can be written over two or more lines. Also, two or more statements can be written on the same line by separating them with semicolons (the JScript statement termination character)

block = group of JScript statements surrounded by braces ({}); treated as a single statement; block itself is not terminated with semicolon; typically used to define functions and conditions; a block is not a new scope (unlike C++)

 

6.1.1      Why Use JavaScript?

 

 

6.1.2      History

 

In the mid-1990s, Netscape introduced LiveScript in Navigator 2.0b1.  By the end of 1995, Sun endorsed LiveScript as a tool for manipulating Java applets.  So, LiveScript was renamed JavaScript (despite the fact that JavaScript is nothing like Java).

 

6.1.3      References

 

http://www.daaq.net/old/javascript/index.php EXCELLENT TUTORIAL

 

http://www.jibbering.com/faq/ (comp.lang.javascript FAQ)

http://webreference.com/programming/javascript/

http://www.cgi-fan.com

http://msdn.microsoft.com/library/default.asp?url=/workshop/entry.asp

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsoriJScript.asp

http://webreference.com/programming/javascript/

http://www.wdvl.com/Authoring/JavaScript/ - excepts from O’Reilly book

 

 

6.1.4      Capabilities

 

 

6.1.5      Limitations

 

 

6.1.6      Versions

 

There are several versions of JavaScript supported by certain browsers and browser versions. Unfortunately, this can often lead to confusion and incompatibilities. Since Netscape originally introduced JavaScript, JavaScript 1.0 was the language specification supported in Netscape Navigator 2.0. Subsequently, Navigator 3.0 supported new enhancements that comprised JavaScript 1.1. As of 1998, Navigator 4.0 supported JavaScript 1.2.  As of Nov 2001, JavaScript evolved to Version 1.5, supported by Netscape 6 and Internet Explorer 5.5. JavaScript has also been standardized under the name ECMAScript (ECMA-262, ECMA Script Edition 3 – European Computer Manufacturers Association).

 

In parallel, Microsoft attempted to support JavaScript 1.0 in their Internet Explorer 3.0 browser. Known as "Jscript," Microsoft's initial JavaScript support was unreliable and buggy. A push to standardize the language resulted in an "official" version of JavaScript sanctioned by the ECMA. Internet Explorer 4.0 includes robust support for the ECMA standardized JavaScript, which, although it shares much in common with Netscape's JavaScript 1.2, is not exactly equivalent.

 

While programming for any single version of JavaScript is relatively simple, writing code which functions across disparate versions, most notably Navigator 4 and MSIE 4, is one of the major challenges and topics of discussion in JavaScript programming at this time.

 

6.2      DOM (Document Object Model)

 

This object model is a hierarchy of all objects "built in" to JavaScript. Most of these objects are directly related to characteristics of the Web page or browser. The reason we qualify the term "built in" is because the DOM is technically separate from JavaScript itself. That is, the JavaScript language specification, standardized by the ECMA, does not actually specify the nature or specifics of the DOM. Consequently, Netscape and Microsoft have developed their own individual DOM's which are not entirely compatible. Additionally, the DOM stands apart from JavaScript because it could theoretically be accessed by other scripting languages as well.

 

In summary, then, what we refer to as "JavaScript" is actually made up of both JavaScript, the language, and the DOM, or object model which JavaScript can access. In a future WDVL article we will take a closer look at the DOM and its current and future role.

 

Below is a graphical chart illustrating a high-level view of Netscape's DOM. Microsoft's DOM is actually a superset of Netscape's, and so the chart below actually represents a subset of Microsoft's own DOM.

 

 

The main object, the trunk, is always the current browser window, referred to as window. There are many branches off the browser window: the page currently displayed in the window, called document, the current location of the window, called location, the history of all the visited pages of the window, called history, and the value of the status bar, status. Inside each of these branches, you'll find more objects. For example, the document object contains all the elements on a given page: forms, images, and links are all reflected as objects.

 

6.2.1      Specifying a leaf node

 

Whenever you want to access something in the JavaScript tree, you have to "climb" up to it. To better understand this, let's create our own example of "climbing the tree" using a simple HTML document:

 

<html>

<body>

<form name="mailform">

<input type="text" name="address">

</form>

</body>

</html>

 

The names of the form and the text input field specified in their HTML tags correspond to the names used by JavaScript. Here we have a form named mailform that contains a text input field named address. To get the text entered by the user, you need to ask for the value of address. That's the value of address in form mailform in the document in the window:

 

window.document.mailform.address.value

 

Because it is very common to access elements in the current page, JavaScript lets you take a shortcut and start climbing the tree at document. Thus, you can also access the text of the address field as:

 

document.mailform.address.value

 

6.2.2      Properties and Methods of Common Objects

 

Object Name

Property/Method Name

Description

Date

getDay()

returns current day; 0 (Sun) – 6 (Sat)

Date

getFullYear()

returns current year

Date

getHours()

returns current hour

Date

getMinutes()

returns current minute

Date

getMonth()

returns current month; 0 (Jan) – 11 (Dec)

Date

getSeconds()

returns current second

math

floor()

 

 

6.3      Embedding

 

6.3.1      script tag

 

JavaScript code is typically embedded into an HTML document using the SCRIPT tag. You are free to embed as many scripts into a single document as you like, using multiple SCRIPT tags. A script embedded in HTML with the SCRIPT tag uses the format:

 

<script language="JavaScript">

<!--

document.write("Hello World!");

//-->

</script>

 

The browser considers everything within the script tag to be pure JavaScript and nothing else. This is where most of your scripts will reside. script tags can be placed anywhere inside an HTML document, in the head or in the body.  Typically, define functions in the head so that they are available before the body loads.  In this case, the script tag is placed where the script does its work of printing out a page--in the body. In other documents, you'll see functions defined in a script tag in the head of the document and then called from other script tags placed elsewhere on the page.

 

The LANGUAGE attribute is optional, but recommended. VBScript, a scripting language based on the Visual Basic programming language, can also be used. But VBScript is supported only in Internet Explorer, which limits its practical use.  You may specify that a section of code only be executed by browsers which support a particular version of JavaScript; for instance:

 

<script language="JavaScript1.2">

 

6.3.2      Attribute/Value pair in a tag

 

 

6.3.3      Sourcing Code Files

 

Another attribute of the SCRIPT tag, SRC, can be used to include an external file containing JavaScript code rather than code embedded into the HTML:

 

<script language="JavaScript" src="corefunctions.js">

</script>

 

The external file is simply a text file containing JavaScript code, and whose filename ends with the extension ".js". Note that although some version 3 browsers support the SRC attribute, it only functions reliably across platforms in the version 4 browsers.

 

The advantage of doing this is that the code is not visible to the user should they try to view the source.  However, they can view the included file by saving the complete web page.

 

Scripts can be placed inside comment fields to ensure that your JavaScript code is not displayed by old browsers that do not recognize JavaScript. The markup to begin a comment field is <!-- while you close a comment field using //-->. This practice is certainly optional, but considered good form when your page is likely to be visited by older browsers. Certainly, as older browsers fade away, this practice will likely become unnecessary.

 

6.4      Comments

 

single line = two forward slashes (//)

multi-line = /* one or more lines */

 

 

6.5      Operators

 

6.5.1      Unary

 

 

6.5.2      Binary

 

+

string concatenation, numeric addition

=, +=, -=, *=, /=

assignment

==, !=

equality (coerces data types, so “1” == 1 is true)

===

strict equality (does not coerce data types, so “1” === 1 is false)

>, <, >=, <=

Comparison (string and numeric)

&&

Logical AND

||

Logical OR

 

6.5.3      Ternary

 

 

6.6      Variables

 

6.6.1      Names

 

Variable names are case-sensitive in JavaScript but not in Jscript, so don’t rely on case-sensitivity.  Names must begin with letters or underscore, and can only include letters, numbers and underscore.

 

6.6.2      Declaration

 

Declared using the var statement.  If not declared before first use (considered “unsafe”), the variable is initialized to the value undefined and has global scope.  When declared in a procedure, its scope is localized.  To declare a variable with no initial value, say:

 

var myvariable = null;

 

null behaves like the number 0; undefined behaves like the special value NaN (Not a Number).  They always compare to be equal.

 

Implicit declaration (don’t use keyword var):

 

      myvariable = “somestring”;

 

6.6.3      Dereferencing

 

Can’t use a variable that has never been declared.

 

To (de-)reference a variable, simply specify the variable name (e.g no leading ‘$’ like in Perl)

 

6.6.4      Data Types

 

Data type is not declared, it’s implicit in how the variable is used.

 

6.6.4.1       Primitive

 

 

6.6.4.2       Composite (Reference)

 

 

6.6.4.3       Special

 

 

6.6.5      Scope

 

Variables are either global or local.  It’s local if defined within a function using the var keyword; otherwise it’s global.

 

6.7      Statements

 

If a statement is on a line by itself, the terminating semicolon (;) can be omitted, but it is best practice to include it.

 

Statements can be grouped together with braces, e.g.:

 

{ a = b + 3; c = a – 4; }

 

6.8      Special Characters

 

JScript provides special characters that allow you to include in strings some characters you cannot type directly. Each of these characters begins with a backslash. The backslash is an escape character you use to inform the JScript interpreter that the next character is special.

 

Escape Sequence

Character

\b

Backspace

\f

Form feed

\n

Line feed (newline)

\r

Carriage return

\t

Horizontal tab (Ctrl-I)

\'

Single quotation mark

\"

Double quotation mark

\\

Backslash

 

Notice that because the backslash itself is used as the escape character, you cannot directly type one in your script. If you want to write a backslash, you must type two of them together (\\).

 

6.9      Control Flow

 

6.9.1      if

 

if (condition) statement;

if (condition) { block }

if (condition) { block } else { block }

variable = (condition) ? then-value : else-value;

 

6.9.2      switch

 

Switch matches an expression with a specified case, and executes the statements defined for that case. In essence, the switch statement is a sort of shorthand for combining many implied if statements together.

 

switch (expression){

   case label :

      statement;

      break;

   case label :

      statement;

      break;

   ...

   default : statement;

}

 

For example, imagine that you wanted to execute different sets of statements depending on whether favoritePet was "dog," "cat," or "iguana." Note that the break; statement prevents any cases below the match from being executed. The default case is matched if none of the cases match the expression.

 

switch (favoritePet){

   case "dog" :

      statements;

      break;

   case "cat" :

      statements;

      break;

   case "iguana" :

      statements;

      break;

   default : statements;

}

 

6.9.3      loops

 

for (initialization; invariant; increment) { block }

 

for (prop in object) { block }                enumerate properties in an object

 

 

 

while (condition) { block }

 

do { block } while (condition);

 

break exits a loop

continue starts next loop iteration

 

 

 

 

6.10Functions/Methods

 

create new scope

 

A JavaScript function is quite similar to a "procedure" or "subroutine" in other programming languages. A function is a discrete set of statements which perform some action. It may accept incoming values (parameters), and it may return an outgoing value. A function is "called" from a JavaScript statement to perform its duty. A method is simply a function that is contained in an object. For instance, a function that closes the current window, named close(), is part of the window object; thus, window.close() is known as a method.

 

Generally it's best to define the functions for a page in the HEAD portion of a document. Since the HEAD is loaded first, this guarantees that functions are loaded before the user has a chance to do anything that might call a function. Alternately, some programmers place all of their functions into a separate file, and include them in a page using the SRC attribute of the SCRIPT tag. Either way, the key is to load the function definitions before any code is executed.

 

6.10.1 Built-in

 

eval()

 

This causes File->Print to be executed:

 

<script>parent.print()</script>

 

6.10.2 Definition

 

function convert(inches) {

   feet = inches / 12; // These five statements are in a block.

   miles = feet / 5280;

   nauticalMiles = feet / 6080;

   cm = inches * 2.54;

   meters = inches / 39.37;

   return feet;

}

 

6.10.3 Execution

 

myfeet = convert(12);

 

6.11Objects

 

Tangible elements that can be referred to and manipulated by JavaScript.  Collections of properties and methods. A method is a function that is a member of an object. A property is a value or set of values (in the form of an array or object) that is a member of an object.

 

Arrays and objects are handled almost identically in JScript - arrays are a special kind of object. Both can have arbitrary properties assigned to them.

 

Objects contain constructs which possess a set of values.  Each value is reflected in an individual property of that object.  Objects are a critical concept and feature of JavaScript. A single object may contain many properties.  Each property acts like a variable reflecting a certain value. JavaScript can reference a large number of "built-in" objects which refer to characteristics of a Web document. For instance, the document object contains properties which reflect the background color of the current document, its title, and many more. For a fuller explanation of the built-in objects of JavaScript, see the section on "Document Object Model".

 

6.11.1 Object Properties

 

A property is an identifier appended to an object name with a period.

 

6.11.2 Objects as Associative Arrays

 

Normally, you use the dot operator "." to access an object's properties. For example:

 

myObject.aProperty

 

Here, the property name is an identifier. You can also access an object's properties using the index operator "[]". Here, you are treating the object as an associative array. An associative array is a data structure that allows you to dynamically associate arbitrary data values with arbitrary strings. For example,

 

myObject["aProperty"] // Same as above.

 

Although the use of the index operator is more commonly associated with accessing array elements, when used with objects, the index is always the property name expressed as a string literal.  Notice the important difference between the two ways of accessing object properties:

 

Operator

The property name is treated as

Meaning the property name

Dot "."

an identifier

cannot be manipulated as data

Index "[]"

a string literal

can be manipulated as data

 

This difference becomes useful when you do not know what the property names will be until runtime (for example, when you are constructing objects based on user input).   Here are two equivalent methods:

 

for (prop in document) {

  eval("myprop = document." + prop);

  document.writeln("document." + prop + " = " + myprop);

}

 

for (prop in document) {

  document.writeln("document." + prop + " = " + document[prop]);

}

 

6.11.2.1   Length

 

The difference between arrays and objects is that arrays have a length property (the number of elements in an array), but objects don’t.  If you create an array with 3 elements, but you add an element at index 9, the length becomes 10.  If you create an array with 10 elements, but set someArray.length to 3, elements 3 through 9 will be deleted.

 

6.11.2.2   Expando

 

All objects can add or remove properties dynamically at run time.  An expando property can be a simple identifier appended to the object name with a period, or an arbitrary string appended to the object name in square brackets (like an array index).  Expando properties don’t affect the length property of arrays.

 

6.11.3 Object Types

 

JScript supports four kinds of objects:

 

 

6.11.3.1   Intrinsic

 

Microsoft JScript provides eleven intrinsic (or “built-in”) objects:

 

6.11.3.1.1  Array

 

create using new operator and Array constructor. indexed by integers starting with 0

 

var theMonths = new Array(12);

theMonths[0] = "Jan";

 

var theMonths = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun",

"Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

 

Pseudo-multi-dimensional array (actually storing an array as an element of another array):

 

someArray[index1][index2]

 

6.11.3.1.2  Boolean

 

6.11.3.1.3  Date

 

create using new operator and Date constructor

 

aDate.getFullYear();

aDate.getDate();

 

6.11.3.1.4  Function

 

6.11.3.1.5  Global

 

6.11.3.1.6  Math

 

only one Math object; has a number predefined properties and methods

 

Math.PI     // 3.14159

Math.pow(aNumber, aExponent)

 

6.11.3.1.7  Number

 

only one Number object; has some predefined properties:

 

Number.MAX_VALUE

Number.MIN_VALUE

Number.NaN – Not a Number; don’t compare against this object, instead use isNaN() instead

 

6.11.3.1.8  Object

 

6.11.3.1.9  RegExp

 

6.11.3.1.10            Error

 

6.11.3.1.11            String

 

treat any string or number as if it were an object

 

aChunk = aString.substring(4, 7);

 

length = aString.length;

 

6.11.3.2   User-defined

 

6.11.3.2.1  Prototype

 

Define a constructor function, using the keyword this to create properties:

 

// pasta is a constructor that takes four parameters.

function pasta(grain, width, shape, hasEgg)

{

    // What grain is it made of?

    this.grain = grain;

 

    // How wide is it? (number)

    this.width = width;    

 

    // What is the cross-section? (string)

    this.shape = shape;  

 

    // Does it have egg yolk as a binder? (boolean)

    this.hasEgg = hasEgg;

 

    this.toString = pastaToString;

}

 

Create instance of object using new operator.  You can add properties “at will” to one instance of an object to change that instance, but those properties do not become part of the definition of other objects made with the same constructor.

 

To include methods (functions) in the definition of an object, include a property in the constructor function that refers to a function defined elsewhere.

 

function pastaToString()

{

    // return the properties of the object

 

    return "Grain: " + this.grain + "\n" +

        "Width: " + this.width + "\n" +

        "Shape: " + this.shape + "\n" +

        "Egg?: " + Boolean(this.hasEgg);

}

 

var spaghetti = new pasta("wheat", 0.2, "circle", true);

// This will call toString() and display the properties

// of the spaghetti object (required Internet Explorer).

window.alert(spaghetti);

 

6.11.3.2.2  Direct instance of an object

 

Despite the awkward sound name, a "direct instance of an object" simply means creating a new single object, such as myPetDog:

 

myPetDog=new Object();

myPetDog.name="Barney";

myPetDog.breed="beagle";

myPetDog.year=1981;

 

Assigning a method to your new object is also simple. Assume that you already have coded a function named woof(), which causes a barking sound to play:

 

myPetDog.woof=woof;

 

6.11.3.3   Host

 

provided by the host (such as window and document in Internet Explorer) e.g. window and document.

 

6.11.3.4   Active X

 

external components

 

6.12Internet Explorer Scripting Object Model

 

http://msdn2.microsoft.com/en-us/library/ms970457.aspx

 

6.12.1 The Window Object

 

The Window object is the object that represents the Internet Explorer. The properties, methods, and events listed below can be called directly in VBScript without qualification—meaning that the Window object does not need to be specified.

 

Properties:

 

Property

Type

Description

VBScript Usage

Name

String

Returns the name of the current window.

MsgBox Name

Parent

Object

Returns a reference to the Parent Set object.

MyObject=Parent

Self

Object

Returns a reference to the Window object itself.

Set MyObject=Self

Top

Object

Returns a reference to the topmost Window object.

Set MyObject=Top

Location

Object

Returns a reference to the Location object (the URL of the current page).  Setting this property to a URL (string) browses the specified URL.

Set MyObject= Location

DefaultStatus

String

Returns or sets the text in the lower left corner of the status bar. (At this writing, this property does not set the specified string to be the default status message. Therefore, it is the same as calling Status.)

DefaultStatus="Ready"

Status

String

Returns or sets the text in the lower left corner of the status bar.

Status="Busy"

Frames

Object

Returns a reference to the Frames array.

Set MyObject= Frames(1)

History

Object

Returns a reference to the History object of the current window.

Set MyObject=History

Navigator

Object

Returns a reference to the Navigator object of the current window.

Set MyObject= Navigator

Document

Object

Returns a reference to the Document object of the current window.

Set MyObject= Document

 

Methods:

 

Method

Return Type

Description

Usage

Alert

None

Displays an OK message box.

Alert "Stop that!"

Confirm

Boolean

Displays an OK/Cancel message box and returns a Boolean value. True if user clicked on OK; False if not.

MyVar=Confirm ("Are you sure?")

Prompt

String

Displays an OK/Cancel input box that returns the text in the input box. The message and the initial text in the input boxcan be specified.

MyVar=Prompt ("Enter your name", "name")

Open

Object

Opens a new window.

open("url", "windowName", "windowFeatures", width, height)

Close

None

Closes the window.

Close

SetTimeout

Long

Executes the code contained in the string after msec milliseconds have elapsed.

MyID=SetTimeout ("string", msec)

ClearTimeout

None

Clears the timer specified.

ClearTimeout(MyID)

Navigate

None

Jumps to a specified URL.

Navigate "http://www.vb-bootcamp.com"

 

Events:

 

Event

Arguments

Description

Usage

OnLoad

None

Fires when page is loaded

<BODY OnLoad="MySub">

OnUnload

None

Fires when page is unloaded

 

<BODY OnUnload="MySub">

 

 

6.12.2 The Document Object

 

The Document object represents the current HTML page in the browser. The Document object also represents any object on the HTML page, such as a link, a form, a button, or an ActiveX object. The properties and methods for the Document object must be fully qualified when used. The Document object supports many properties and methods that modify the HTML page. These properties and methods, such as LinkColor and Write, must be used inline when the HTML page is loading. These properties and methods cannot be called after the HTML page is loaded because the Internet Explorer parses the HTML only during page load. VBScript code can be executed inline as the load occurs. The following code shows an example where text is being written to an HTML page and the background color is being set to white:

 

<SCRIPT LANGUAGE="VBScript">

    Document.Write "<H2>Inline HTML modification</H2>"

    Document.BGColor="#FFFFFF"

</SCRIPT>

 

Executing inline code to modify an HTML page while it loads is known as immediate execution. Immediate execution is a valuable technique because it allows you to create web pages that are different each time they are loaded. As a simple example, the following code displays the date of the last update for the web page:

 

Document.Write "<P><CENTER>"

Document.Write "Page last updated"

Document.Write Document.LastModified

Document.Write "</CENTER><P>"

 

This technique can be expanded to display new pictures or text on the basis of the current date, or even randomly.

 

Properties:

 

Property

Type

Description

Usage

LinkColor

String

Returns or sets the link color. Accepts a string input representing the hexadecimal color value or a specific color command

Document.LinkColor= "#FF0000" Document.LinkColor= "Red"

ALinkColor

String

Returns or sets the anchor color. Accepts a string input representing the hexadecimal color value or a specific color command.

Document.ALinkColor="#FF0000" Document.ALinkColor="Red"

VLinkColor

String

Returns or sets the visited link color. Accepts a string input representing the hexadecimal color value or a specific color command.

Document.VLinkColor="#FF0000" Document.VLinkColor="Red"

BGColor

String

Returns or sets the background color. Accepts a string input representing the hexadecimal color value or a specific color command.

Document.BGColor="#FF0000" Document.BGColor="Red"

FGColor

String

Returns or sets the foreground color. Accepts a string input representing the hexadecimal color value or a specific color command.

Document.FGColor = "#FF0000" Document.FGColor = "Red"

Anchors

Object

Returns an Anchors array.

Set MyObject= Document.Anchors(1)

Links

Object

Returns a Links array.

Set MyObject= Document.Links(1)

Forms

Object

Returns a Forms array.

Set MyObject= Document.Forms(1)

Location

String

Returns a string representing the complete URL for the current document.

MyVar= Document.Location

LastModified

String

Returns a string representing the date when the current page was last modified.

MyVar= Document.LastModified

Title

String

Returns the read-only title of the current HTML page.

MyVar= Document.Title

Cookie

String

Returns or sets the cookie for the current document.

MyVar= Document.Cookie

Referrer

String

Returns the URL of the referring document.

MyVar= Document.Referrer

 

Methods:

 

Method

Return Type

Description

Usage

Write

None

Writes the given string into the current document.

Document.Write "Hello"

WriteLn

None

Writes the given string into the current document with the addition of a newline character at the end. (This works only if the scripting section is surrounded by <PRE></PRE> tags.)

Document.WriteLn "Hello"

Open

None

Opens the document stream for output.

Document.Open

Close

None

Updates the screen to display all the strings written after the last Open method call.

Document.Close

Clear

None

Closes the document output stream and writes the data to the screen. Empties the current document and clears your script (along with the rest of the document).

Document.Clear

 

6.12.3 The Form Object

 

The Form object represents a form created by the <FORM></FORM> tags. The Form object can be accessed as a property of the Document object. Using forms in VBScript is similar to using forms in Visual Basic for Applications. Any controls contained within the <FORM></FORM> tags are accessed with the Form.Control.Property syntax. Additionally, the Internet Explorer provides complete support for all of the events for a control contained in a form. Tables 3-8, 3-9, and 3-10 show the properties, method, and event for the Form object.

 

Properties:

 

Property

Type

Description

Usage

Action

String

Returns or sets the ACTION attribute.

MyForm.Action="http://www.vb-bootcamp"

Encoding

String

Returns or sets the ENCODING attribute.

MyForm.Encoding="text/html"

Method

String

Returns or sets the METHOD attribute.

MyForm.Method="POST"

Target

String

Returns or sets the TARGET attribute.

MyForm.Target= "NewWindow"

Elements

Object

Returns an Elements array.

Set MyObject=MyForm.Elements(1)

Hidden

 

Not yet implemented.

 

 

Method:

 

Method

Return Type

Description

Usage

Submit

None

Submits form contents.

MyForm.Submit

 

Event:

 

Event

Arguments

Description

Usage

OnSubmit

None

Fires when form contents are submitted

MyForm.OnSubmit = “VBScript code”

 

6.12.3.1   The Elements Array

 

The Elements array represents all of the controls in the current HTML page. These controls can be intrinsic controls or controls inserted with the <OBJECT> </OBJECT> tags.

 

6.13Navigator Built-In Objects

 

6.13.1 navigator

 

Reveal info about the type of browser accessing a page.  The browser object in JavaScript is called “navigator” even if the browser itself is IE.

 

 

appVersion returns a string containing both the major version number and other textual info (e.g. operating system version and local language).

 

appName.toLowerCase(string)

 

6.13.2 window

 

 

 

6.13.3 location

 

 

6.13.4 history

 

 

6.13.5 document

 

 

 

 

6.13.6 form

 

 

javascript\Intro to JavaScript - form elements.htm

 

6.13.7 date

 

 

6.13.8 string

 

 

6.13.9 math

 

 

6.14Global functions not associated with objects

 

 

6.15Events and Event Handlers

 

JavaScript programs are typically event-driven. Events are actions that occur on the Web page, usually as a result of something the user does, although not always. For example, a button click is an event, as is giving focus to a form element; resizing the page is an event, as is submitting a form. It is these events which cause JavaScript programs to spring into action. For example, if you move your mouse over this phrase, a message will pop-up, courtesy of JavaScript.

 

An event, then, is the action that triggers an event handler. The event handler specifies which JavaScript code to execute. Often, event handlers are placed within the HTML tag that creates the object on which the event acts:

 

<tag attribute1 attribute2 onEventName="javascript code;">

 

For example, a hyperlink is subject to a MouseOver event, meaning that its event handler will be triggered when the mouse passes over the link. Therefore, you place the event handler for a hyperlink's MouseOver inside the A tag:

 

<a href="" onMouseOver="popupFunc();">

 

The JavaScript which is called by the event handler may be any valid JavaScript code: a single statement or a series of statements, although most often it is a function call.

 

The set of all events which may occur, and the particular page elements on which they can occur, is part of the Document Object Model (DOM), and not JavaScript itself (see the earlier section "Document Object Model"). As a result, Netscape and Microsoft do not share the exact same set of events, nor are all page elements subject to the same events between browsers. For example, Internet Explorer 4 supports a MouseOver event for an image while Navigator 4 does not.

 

The table below illustrates some of the most commonly used events supported in both DOM's:

 

Event

Occurs when...

Event Handler

click

User clicks on form element or link

onClick

change

User changes value of text, textarea, or select element

onChange

focus

User gives form element input focus

onFocus

blur

User removes input focus from form element

onBlur

mouseover

User moves mouse pointer over a link or anchor

onMouseOver

mouseout

User moves mouse pointer off of link or anchor

onMouseOut

select

User selects form element's input field

onSelect

submit

User submits a form

onSubmit

Reset

User resets a form

onReset

resize

User resizes the browser window

onResize

load

User loads the page in the Navigator

onLoad

unload

User exits the page

onUnload

 

6.15.1 onClick Syntax

 

 

 

6.15.2 onSubmit Syntax

 

 

 

6.15.3 onReset Syntax

 

 

6.15.4 onChange Syntax

 

 

 

6.15.5 onLoad Syntax

 

 

 

6.15.6 onUnload Syntax

 

 

6.15.7 onMouseOver Syntax

 

 

 

6.16Intrinsic HTML Controls

 

6.16.1 Button

 

The intrinsic Button control is simply used to supply a general-purpose button control on a form. The button is implemented with the <INPUT> tag.

 

Attributes

NAME  A string representing the name of the Button control 

VALUE  A string representing the text that appears on the button 

 

 

Events

OnClick  Fires whenever the control is clicked 

OnFocus  Fires when the control receives the focus 

 

 

Syntax:

 

<INPUT TYPE="BUTTON" [NAME="string"] [VALUE="string"] [OnClick="subroutine"] [OnFocus=" subroutine"]>

 

Example:

 

<FORM>

<INPUT TYPE="BUTTON" NAME="btnOne" VALUE="Push Me!">

</FORM>

 

6.16.2 Checkbox

 

The intrinsic CheckBox control implements a simple check box by using the <INPUT> tag. When a form containing CheckBox controls is submitted to the server, only the information from the selected check boxes is submitted.

 

Attributes

NAME  A string representing the name of the CheckBox control 

VALUE  A string representing the value of the control when submitted (by default, this value is ON) 

CHECKED  An option that causes the check box to be checked by default 

 

 

Events

OnClick  Fires whenever the control is checked 

OnFocus  Fires when the control receives the focus 

 

 

Syntax

<INPUT TYPE="CHECKBOX" [NAME="string"] [VALUE="string"] [CHECKED] [OnClick="subroutine"][OnFocus=" subroutine"]>

 

Example

<FORM>

<INPUT TYPE="CHECKBOX" NAME="chkOne" VALUE="Checked" CHECKED>

</FORM>

 

6.16.3 Hidden

 

The intrinsic Hidden control is used to provide data that is invisible to the user in the form. Hidden controls are useful when you want to pass data from a form to another process and send along key information that is supplied by the web page and not the user.

 

Attributes

NAME  A string representing the name of the Hidden control 

VALUE  A string representing the default value of the control 

 

 

Syntax

<INPUT TYPE="HIDDEN" [NAME="string"] [VALUE="string"]>

 

Example

<FORM>

<INPUT TYPE="HIDDEN" NAME="txtOne" VALUE="SECRET_CODE">

</FORM>

 

6.16.4 Password

 

The intrinsic Password control is similar to a Text control, but when the user enters data into a Password control, only asterisks appear. This control is useful for preventing others from seeing the data on the screen, but be aware that the ASCII text is sent directly over the network without encryption.

 

Attributes

NAME  A string representing the name of the Password control 

VALUE  A string representing the default value of the control 

SIZE  An integer representing the length of the control in characters 

MAXLENGTH  An integer representing the maximum number of characters allowed in the control 

 

 

Events

OnFocus  Fires when the control receives the focus 

OnBlur  Fires when the control loses the focus 

 

 

Syntax

<INPUT TYPE="PASSWORD" [NAME="string"] [VALUE="string"] [SIZE="integer"] [MAXLENGTH="integer"] [OnFocus="subroutine"] [OnBlur="subroutine"] >

 

Example

<FORM>

<INPUT TYPE="PASSWORD" NAME="txtOne" VALUE="changeme" SIZE="10"

MAXLENGTH="8">

</FORM>

 

6.16.5 Radio

 

The intrinsic Radio control allows a user to select one choice from a number of options. Radio controls are also called option buttons. Radio controls can be grouped by using the same NAME attribute.

 

Attributes

NAME  A string representing the name of the Radio control 

VALUE  A string representing the value of the control when submitted (each radio button should have a unique value) 

CHECKED An option that causes the Radio control to be selected by default 

 

 

Events

OnClick  Fires when the control is clicked 

OnFocus  Fires when the control receives the focus 

 

 

Syntax

<INPUT TYPE="RADIO" [NAME="string"] [VALUE="string"] [CHECKED] [OnClick="subroutine"] [OnFocus=" subroutine"]>

 

Example

<FORM>

<INPUT TYPE="RADIO" NAME="OPTIONS" VALUE="One" CHECKED>One

<INPUT TYPE="RADIO" NAME="OPTIONS" VALUE="Two">Two

<INPUT TYPE="RADIO" NAME="OPTIONS" VALUE="Three">Three

</FORM>

 

6.16.6 Reset

 

The intrinsic Reset control clears all the text fields in the current form. The Reset control appears in the browser as a button and by default has the caption "Reset."

 

Attributes

NAME  A string representing the name of the Reset control 

VALUE  A string representing the text that appears in the Reset button caption 

 

 

Events

OnClick  Fires whenever the control is clicked 

OnFocus  Fires when the control receives the focus 

 

 

Syntax

<INPUT TYPE="RESET" [NAME="string"] [VALUE="string"] [OnClick="subroutine"] [OnFocus="subroutine"]>

 

Example

<FORM>

<INPUT TYPE="TEXT">

<INPUT TYPE="RESET" VALUE="Reset Me">

</FORM>

 

6.16.7 Select

 

The intrinsic Select control is used to create a list of selections. It is similar to the ComboBox control in Visual Basic. The Select control is implemented in HTML with the <SELECT></SELECT> tags. The <OPTION> tag is used to identify each element in the list.

 

Attributes

NAME  A string representing the name of the Select control 

SIZE  An integer representing the number of items in the list that are visible at one time 

MULTIPLE  An option that allows multiple items in a list to be selected 

SELECTED  An option that causes the element in the list to be selected by default 

 

 

Events

OnFocus  Fires when the control receives the focus 

OnBlur  Fires when the control loses the focus 

OnChange  Fires when the control is changed 

 

 

Syntax

<SELECT NAME="string" [SIZE="integer"] [MULTIPLE] [OnFocus="subroutine"][OnBlur=" subroutine"][OnChange="subroutine "] <OPTION [SELECTED] VALUE="string">Item </SELECT>

 

Example

<FORM>

<SELECT NAME="FirstLanguage" MULTIPLE>

<OPTION VALUE="1">Visual Basic

<OPTION SELECTED VALUE="2">VBScript

<OPTION VALUE="3">C++

</SELECT>

</FORM>

 

6.16.8 Submit

 

The intrinsic Submit control is a button used to pass all the elements in a form to a back-end process. When a form is submitted, the data entered into the input controls is sent as ASCII text to the process identified in the ACTION attribute of the form. Every form with more than one field must have a Submit control. Typically, you have one, and only one, Submit control, but it is possible to have more than one.

 

Attributes

NAME  A string representing the name of the Submit control 

VALUE  A string representing the text that appears in the Submit button caption 

 

 

Events

OnClick  Fires whenever the control is clicked 

OnFocus  Fires when the control receives the focus 

 

 

Syntax

<INPUT TYPE="SUBMIT" [NAME="string"] [VALUE="string"] [OnClick="subroutine"] [OnFocus="subroutine"]>

 

Example

<FORM METHOD="POST" ACTION="http://www.vb-bootcamp.com/test">

<INPUT TYPE="TEXT">

<INPUT TYPE="SUBMIT" VALUE="Submit Form">

</FORM>

 

6.16.9 Text

 

The intrinsic Text control is used as an input device to receive text. It is quite similar to the TextBox control in Visual Basic. The intrinsic Text control is implemented with the <INPUT> tag.

 

Attributes

NAME  A string representing the name of the Text control 

VALUE  A string representing the default value of the control 

SIZE  An integer representing the length of the control in characters 

MAXLENGTH  An integer representing the maximum number of characters allowed in the control 

 

 

Events

OnFocus  Fires when the control receives the focus 

OnBlur  Fires when the control loses the focus 

OnSelect  Fires when the contents of the control are selected 

OnChange  Fires when the control is changed 

 

 

Syntax

<INPUT TYPE="TEXT" [NAME="string"] [VALUE="string"] [SIZE="integer"] [MAXLENGTH="integer"] [OnFocus="subroutine"] [OnBlur="subroutine"] [OnSelect="subroutine"] [OnChange=" subroutine"]>

 

Example

<FORM>

<INPUT TYPE="TEXT" NAME="Text1" VALUE="Default Text" SIZE="50" MAXLENGTH="30">

</FORM>

 

6.16.10                     Textarea

 

The intrinsic TextArea control is similar to the Text control but allows multiline user input. Text areas are created with the <TEXTAREA></TEXTAREA> tags.

 

Attributes

NAME  A string representing the name of the TextArea control 

ROWS  An integer representing the height of the control in lines 

COLS  An integer representing the width of the control in characters 

 

 

Events

OnFocus  Fires when the control receives the focus 

OnBlur  Fires when the control loses the focus 

OnSelect  Fires when the contents of the control are selected 

OnChange  Fires when the control is changed 

 

 

Syntax

<TEXTAREA [NAME="string"] [ROWS="integer"] [COLS="integer"] [Onfocus="subroutine"] [OnBlur="subroutine"] [OnSelect="subroutine"] [OnChange="subroutine"]></TEXTAREA>

 

Example

<FORM>

<TEXTAREA NAME="txtWords" ROWS="20" COLS="20">

</TEXTAREA>

</FORM>

 

6.17Message Boxes (user I/O)

 

Each of these are methods of the window object.

 

6.17.1 alert()

 

Notification with single button “OK”, e.g.

 

<input type="button" value="Alert Button"

onClick="alert('You clicked the alert button');"

>

 

6.17.2 confirm()

 

Notification with two buttons (“OK” and “Cancel”).  Returns boolean result, e.g.

 

<script type="text/javascript">

 

if (confirm('OK to delete universe?')) {

  document.write('Deleting universe.  Stand by.');

}

else {

  document.write('Universe saved.');

}

 

</script>

 

6.17.3 prompt(message, default)

 

Obtains a string from the user and provides two buttons (“OK” and “Cancel”).  Returns user’s string or “null” if user clicks “Cancel”.

 

6.18Forms

 

 

 

 

 

this.value = the value of the current field

 

6.18.1 Form Field Validation

 

The process of evaluating form input from a user and comparing it to a set of rules is generally referred to as form field validation. Specifically, validating a field involves accessing the user's input, evaluating it for characteristics such as data type, length, and format, and either accepting the input or rejecting is as invalid. Form field validation is a critical component of database interaction, because invalid data can cause problems when inserted into a database: everything from generating an error to causing breaches in security. As a result, any data that is inserted into a database must first be validated. Any user-supplied data that will be passed to a server-side script should also be thoroughly evaluated. CGI (Common Gateway Interface) and other server-side scripts can introduce serious vulnerabilities on the Web server if they take action on user input that has not been validated.

 

Names are notoriously difficult to validate. Some people use only initials. Some use only one name. It's impossible to intelligently guess how long a name should be. Given the broad range of possibilities, there is little that can be done to validate input for name fields. There are two possible checks. First, you can check to see that the field was not left empty. Second, you could make sure there aren't a ridiculously high number of characters in the field. If the HTML in the top example (below) was used, then the JavaScript syntax in the bottom example could be used to write a validation script.

 

 

For the example, a single field is used, and there are instructions that the user should enter the data in the format 999-999-9999. To validate user input, you could first check its length. According to the instructions, the user should always enter 12 characters. Second, you can look for the dashes. There should be dashes at the third and seventh index numbers. And finally, you can make sure that the area code, exchange, and local numbers are numeric. If the HTML in the top example was used, then the JavaScript syntax in the bottom example could be used to access the user's data.

 

 

There are many characteristics of an e-mail address that can be validated.

 

 

 

With a completed validation script, all of the individual checks are built into a single function. The completed script also has a few additional statements. Anytime an error is discovered, three things are accomplished: an alert is sent to inform the user of the mistake; the focus() method is used to move the insertion point back to the offending field; and finally, return false is used to stop the function and indicate to the browser that it should not submit the data. The final statement in the function is return true. If the processing reaches this point in the script, all of the checks completed and no errors were found. By returning true, the script indicates to the browser that it should submit the data.

 

The best time to run the validation script is after the user clicks the Submit button. By attempting to submit the form, the user indicates that he or she is done entering data, so that's the time to evaluate what's there. The validation script is initiated by using the onSubmit event handler within the <form> tag as shown in the example below. Using the onSubmit event handler inside the <form> tag instructs the browser to execute the script prior to submitting the data to the server. The use of the return keyword before the function call means the browser should wait for a response from the script (either true or false) as an indication of whether the submission should be performed. If the script returns false, the data is not submitted; if the script returns true, it is submitted.

 

 

Element

Description

Form field objects

Is both read and updated; Syntax for referring to a form field is either: document.formname.fieldname or document.forms[index].elements[index]

return keyword

Ends the function; May also be used to return a value to the program using the syntax return expression; In this lab, returns either true or false to tell the browser whether or not to submit the data

focus() method

Moves the focus of the browser to the specified object; Syntax is object.focus()

charAt() method

Returns the character of a string at the specified index number; Syntax is string.charAt(index)

!= not equal to operator

Checks to see whether two operands are unequal; If the two operands are equal, returns false; otherwise returns true

|| OR operator

Checks to see whether any of multiple options is true; If so, returns true; otherwise, returns false

\n new line character

Forces a new line when writing a string; In this lab, forces a new line as you write an alert() statement

 

6.18.2 Radio Buttons

 

Another technique for working with radio buttons is looking at each option to see whether the user has selected that field instead of looking at the values of the radio buttons. There is a checked property available in JavaScript for each radio button. If the button has been selected, the checked property returns true; otherwise it returns false. To perform this evaluation, though, look at the state not of the group (as we do for value) but of the individual buttons within the group. This is problematic because each button in the group has the same name. JavaScript solves this problem by treating radio buttons as an array. To evaluate the value of the checked property for a particular radio button, then, you need to use an index number to the right of the fieldname. For example, use the syntax below to see whether the user has chosen the first radio button in the sample group.

 

 

At some point, you may want to provide an online order form with groups of radio buttons from which the user can make choices. As the user clicks buttons, you'd like to provide a running total of the cost of all the items the user has selected so far. To do this, you could look at the checked property for each radio button and, if the property returns true, add its associated price to a variable. When the user has finished checking each button, the variable would contain the total price for all of the items currently selected. With JavaScript, you could then update the value of a text field on the form with the calculated total. This approach provides valuable feedback to the user as he or she makes choices, rather than having to first make choices, then submit the form, then wait while a server-side script performs the calculation and finally returns the result.

 

 

6.19Drop-Down Lists

 

 

 

 

To overcome this problem, it's important to know the special properties of a select list in JavaScript.

 

First, every select list has a built-in array called options[]. This array is built automatically as the document loads and has one element for each <option> tag in the select list.

 

Second, there is a built-in property of each select list called selectedIndex. This property identifies (by index number) which of the options within the list the user chooses. If the user chooses Wednesday, the selectedIndex property returns 2. (Remember, index numbers start at 0.)

 

 

The most common use of JavaScript with HTML drop-down lists is in creating a navigational scheme. For example, the developer creates a drop-down list that displays page titles to the user. The value associated with each list option is set to the URL (Uniform Resource Locator) of the corresponding page. When the user makes a choice, a script is executed to access the URL of the selected page and then programmatically moves the user to that URL.

 

6.20Browser Windows

 

JavaScript can be used to open new browser windows, close browser windows, control the size and positioning of browser windows, and control what elements (toolbars, menu bar, etc.) of the window are displayed. In JavaScript, the browser window is referred to as the window object.

 

A new browser window can be opened using the open() method of the window object. There are three basic parameters that can be used to control the way the new window opens:

 

            window.open(‘URL’, ‘windowName’, ‘characteristics’);

 

If you want to be able to control the new window using JavaScript statements (rather than HTML controls) from a remote window, the window.open() statement should be assigned to a variable like the syntax example below. This creates a JavaScript window object named myWin that can then be referenced by JavaScript statements in other windows.

 

            myWin = window.open(‘URL’, ‘windowName’, ‘characteristics’);

 

The third parameter in the window.open() statement allows the developer to supply a comma-separated list of properties that will define the new window. The table below lists the optional properties.

 

Property

Value

Description

width

Pixels

Horizontal dimension of window

height

Pixels

Vertical dimension of window

left

Pixels

Distance from left edge of screen to left edge of new window in IE (Internet Explorer)

top

Pixels

Distance from top of screen to top of new window in IE

screenx

Pixels

Distance from left edge of screen to left edge of new window in Netscape Navigator

screeny

Pixels

Distance from top of screen to top of new window in Netscape Navigator

resizable

Yes/no

Allows the user to resize the window

menubar

Yes/no

Displays the menu bar

toolbar

Yes/no

Displays the standard toolbar

scrollbars

Yes/no

Displays scrollbars

status

Yes/no

Displays the status bar

 

To close the current browser window, the simple statement window.close() can be used. This statement does not execute automatically in the primary browser window. Instead, the user is prompted and may override the command. Any new windows that you've opened with JavaScript may, however, be programmatically closed with JavaScript. To close a new window from a script located in some other browser window, the close() statement must be preceded by the JavaScript object name for that window, as shown in the example below.

 

            myWin.close();

 

6.21Frames

 

 

 

 

 

 

 

6.22MouseOver Effects

 

Mouseover effects is the name given to the feedback mechanisms commonly used on Web pages to indicate which item the user's pointer is currently positioned over. It is frequently used in navigational elements to indicate which option will be executed if the user clicks at that moment. These effects give users a sense of control over their browsing experience and a feeling that the site is interacting with them.

 

Most frequently, mouseover effects are created by using JavaScript to dynamically replace one image with another. The site developer created two version of each image: a standard version and a highlighted version. The standard version is displayed in the browser until a mouse pointer is placed over the image at which time the image is immediately replaced with the highlighted version. When the pointer is moved away, the standard version is restored.

 

For the mouseover actions to be effective, the image swapping has to happen instantaneously. In order to achieve that, both the standard and highlighted versions of all the affected images need to be preloaded into the memory of the browser. To preload the images into memory, JavaScript image objects must be created for each version of each image involved. The example below shows the syntax for creating an image object. In this statement, imgObjName is the name you have chosen for the new image object; new is a constructor, indicating that a new object will be created; and Image() indicates the type of object that is being created.

 

imgObjName = new Image();

 

The newly created image object is like an empty container that's designed to hold a certain type of content. No specific graphic has yet been assigned to that container. To associate an actual graphic with this new image object, a second statement like the example below needs to be executed. This statement assigns a URL (Uniform Resource Locator) value to the src property of the object. Now the container has something in it. The new image object has a specific graphic file associated with it. This statement also has the effect of causing the browser to make a new request back to the server to download the specified graphic into memory.

 

imgObjName.src = graphic.jpg;

 

The two previous statements need to be executed for each image that will be part of the effect. So, if there are three visible options and there is an on version and an off version for each option, six pairs of statements need to be executed to get all of the images downloaded into memory. The syntax below is an example of these six pairs of statements. This script should be placed inside the head element of the document so that it can be executed as soon as the browser begins loading the page.

 

 

In the following lab you will create a function to swap in the highlighted image when the mouse pointer is placed over the standard image. The same function is used to restore the standard version when the mouse pointer is moved away. The event handlers you'll be working with are (logically) onMouseOver and onMouseOut. Like all event handlers, onMouseOver and onMouseOut have to be placed inside HTML tags. Unlike other scripts that are placed in the <img> tags in the body of the document, this script needs to be placed inside the anchor tags (<a>) that surround the <img> tags. After all, these effects are generally used in navigational elements, so there are already anchor tags present. A typical HTML syntax is shown in the example below.

 

 

The off or standard version of the image is displayed on the page when it loads. The image is bracketed between anchor tags so that if the user clicks on the image, the page specified by the href attribute is downloaded. In the following lab, you will add the onMouseOver and onMouseOut event handlers to the anchor tag so that when a mouse pointer is moved over or away from the image, the image swapping script will be called. For the script to work, you need to provide two parameters when you call the script: the name of the HTML image tag that will be affected, and the name of the JavaScript image object that should be inserted at that moment. You'll name the script that does the swapping imgChange(). The following example shows how you can add the event handlers to the HTML tags to call the function:

 

 

The function itself will receive the parameters that are passed up to it from the event handlers and perform the image replacement. The code shown below does the work. The pieces of this brief but effective function can be evaluated in the following manner. The function is defined by using the function keyword and assigning a function name, imgChange(). Because this function needs two parameters in order to work, two placeholders are put inside the parentheses: imgname (to represent the name of the HTML image tag) and imgobj (to represent the name of the JavaScript image object that will be inserted).

 

 

The single statement that composes the function refers to the element of the document images array specified in the imgname parameter. It sets the src property of that image to the src property of the JavaScript image object specified in the imgobj parameter.

 

In the example, when the mouse pointer is moved over the alert link, the function is called. The value of the imgname parameter would be 'alertimg' and the value of the imgobj parameter would be alert_on, so the statement looks like the example below. This statement redefines the value of the src property of the HTML <img> tag named 'alertimg' to the value of the src property of the JavaScript alert_on object that was preloaded earlier. In that script, the src property of the alert_on image object points to 'alert_on.jpg'. So the net result is that alert_off.jpg is temporarily replaced with alert_on.jpg. When the mouse pointer moves away from the link, the onMouseOut event handler is activated, calls the same function, and passes parameters indicating that the src property of the same HTML <img> tag should be switched back to alert_off.jpg.

 

6.23Date Objects

 

JavaScript Date objects are necessary for working with any time/date functions: clocks, counters, stopwatches, event countdowns, displaying the current date, etc. In any of these cases, you begin by creating a new JavaScript Date object. The syntax looks like the example below. In this statement, dateObjName is the name you have chosen for the new Date object; new is a constructor, indicating that a new object will be created; and Date() indicates the type of object that is being created. The Date object created by this statement will hold the current date/time according to the user's system clock.

 

dateObjName = new Date();

 

To create a Date object that holds a different date/time, you need to provide a parameter inside the parentheses when you execute the statement. To create a date that represents 3:00 p.m. on New Year's Day in the year 2007, use the syntax below. This statement creates a new Date object based on a string representing a standard date/time format. If the time information were omitted, it would be set to 12:00 midnight (00:00:00) on the specified date.

 

nyd = new Date(‘1/1/2007 15:00:00’);

 

Often when working with Date objects you don't actually want the entire formatted date, only pieces of it. If you want to create a clock, you just need hours, minutes, and seconds. If you want to display a calendar, you just need year, month, and day. To extract only the pieces of a Date object that you need to work with, JavaScript supplies a number of Date methods. The table below illustrates the functionality of commonly used Date methods based on the previously created Date object: nyd.

 

Method in Action

Output

Description

nyd.getYear()

2007

Two-, three- or four-digit year depending on browser; Older browsers used year minus 1900; Newer browsers return four-digit year

nyd.getMonth()

0

Integer representing month of year (0–11)

nyd.getDate()

1

Integer representing day of the month (1–31)

nyd.getDay()

1

Integer representing day of the week(0=Sunday, 6=Saturday)

nyd.getHours()

15

Integer representing hour of day using a
24-hour clock

nyd.getMinutes()

0

Integer representing minutes (0–59)

nyd.getSeconds()

0

Integer representing seconds (0–59)

nyd.getTime()

1167681600000

Integer representing milliseconds difference between this date and 1/1/1970 00:00:00

 

In older browsers, the getYear() method returned a value by taking the current year minus

1900. Until 2000, this returned a two-digit year, but with your Date object representing the year 2007, an older browser executing getYear() would return 107: an obvious problem. To overcome this potential problem with the getYear() method in older browsers, use the syntax below. The first statement executes the getYear() method against the Date object and assigns the output to the variable yr. The second statement checks to see whether the value returned by getYear() is under 1000. If so, it fixes the problem by adding 1900 to the year and reassigning back to the same variable.

 

yr = nyd.getYear();

if (yr < 1000) yr += 1900;

 

The values returned by getDay() and getMonth() methods aren't the actual day and month names. Instead, they are integers that represent the day (0 to 6) and month (0 to 11). Arrays can be used to convert these numeric representations into formatted English month and day names. An array of days of the week can be created using the syntax below.

 

 

 

With arrays for the days of the week and months of the year defined, it is a simple task to go from numbers to names. Once you have acquired the numeric values for day and month, you can get the corresponding names by grabbing the value of the array elements with the same index numbers. In the example below, New Years Day falls on a Monday in 2007.

 

 

6.24Cookies

 

Cookies are small text files stored on a user's machine that are created by Web sites to keep track of user actions and preferences on that site. The primary reason cookies are necessary is the stateless nature of the Web: Web browsers and Web servers do not maintain a persistent connection while the user is looking at a Web page. A connection is maintained only long enough to download the files to the user's cache and then the connection is dropped. Each time a user goes to a new page, the server is unaware of any previous contact with that user. To compensate, developers can leave a little code on the user's machine (a cookie), then check that code when the user makes a new request and at least recognize the fact that the user has been to the site before. Cookies are required in order for Web services like shopping carts to function.

 

JavaScript can be used to read and write cookies. Cookie information is stored as a string property of the document object. The content of cookies can be accessed by assigning the cookie property of the document object to a variable. New cookies can be written or existing cookies updated by assigning a value to the cookie property. To write a cookie, you assign a string value to the cookie property of the document object. The standard syntax looks like the example below. When writing a cookie, you need to provide three parameters within the string: the actual cookie content, a path to which the cookie applies, and an expiration date. Semicolons must be used between the sections and no spaces are allowed.

 

document.cookie = ‘cookieInfoString’;

 

The content portion of the cookie is whatever you'd like it to be. This is where you store the actual cookie data that will be returned to you later. Generally, this information is stored in the format name=value. For example, assume the user filled out a form and you wanted to store their first name so you could create a personalized greeting later. The HTML structure of the form might look like the top example below. The JavaScript used to access the value of the field and assign it to a variable is shown in the bottom example; this value is used later when you write the cookie.

 

 

The second part of the cookie is the path to which the cookie applies. By default, the browser returns cookie information only when files are requested from the same directory where the cookie was generated or one of its subdirectories. This may be useful to prevent too much cookie information from showing up at the same time. On the other hand, you may want to use the information from the cookie for pages in other directories on your site. That's the case in this example. Because you're storing the user's first name, you might want to use that information elsewhere to provide a customized browsing experience. Therefore, set the path to root (/). Setting the path to root indicates to the browser that it should return the cookie information whenever a file is requested anywhere on your server (beginning at the root).

 

Setting an expiration date is the most tedious part of creating a cookie with JavaScript. Because the date is required to be in a specific format, it involves several steps. First, you need to decide when the cookie should expire. If you want it to expire a year from the current date, to calculate the expiration date, you need to start by creating a Date object that reflects the current date/time, as shown in the example below.

 

d = new Date();

 

To calculate a date that represents one year from now, you need to use the getTime() method of the Date object to extract a value that represents the number of milliseconds between 1/1/1970 and now, then add a year's worth of milliseconds to it. You then need to convert it back to a standard date format in GMT (Greenwich Mean Time) as shown in the example below. You now have a Date object named exp that represents an expiration of a year from now.

 

 

To actually create the cookie, you need to take the work in the previous sections and concatenate the content, the path, and the expiration date as shown in the example below.

 

 

When the browser returns cookie information, only the content portion of the cookie is returned. The path and the expiration date are not. In order to read existing cookies, the value of the cookie property can be assigned to a variable, like: cData = document.cookie; Now the cData variable is holding the cookie information. To analyze the contents of the cookie, string methods can be used. For example, to determine whether there is any information in the cookie (whether a cookie exists at all for this user), you can check the length of the cookie using the example below.

 

 

In our example, you stored the user's first name in the cookie and stored the cookie content in the format fname=username. To extract the actual name from the cookie and write a greeting on the page, you could use the code below.

 

 

Cookies are indispensable to Web developers when needing to keep track of customer information from page to page or session to session. They're the only tool that can enable you to recognize a user and recall choices made on a previous page or in an earlier session. All shopping carts utilize cookies, as do any Web portals that allow for the creation of customized start pages.

 

6.25FAQs

 

6.25.1 SaveAs

 

How can I use Javascript to automatically prompt the user the 'Save As..' box to save an HTML Page?

 

Use this function...

 

function saveAsMe (filename)

{

            document.execCommand('SaveAs',null,filename)

}

 

I used this button...

 

<input type=button value="Save As" onclick="saveAsMe('ww.txt');">

 

6.25.2 How to write text to an MS Excel file

 

This function uses ActiveX to get a forms input into a spreadsheet cell.

 

function xlWrite(r,c) {

  var xlApp, xlSheet;

  xlApp = new ActiveXObject("Excel.Application");

  xlApp.Visible = true;

  xlApp.Workbooks.Add();

  xlSheet = xlApp.ActiveSheet;

  xlSheet.Cells(r,c).Value = frm.txt.value;

  xlSheet.SaveAs("C:\\xlText.xls");

 

Note that Excel has a bug and doesn't shut down after calling the

Quit() method when automating from JScript. To work around this

problem, the CollectGarbage() method is used to force JScript's garbage

collection to occur almost immediately.

 

  xlApp.Quit();

  xlApp = null;

  setTimeout("CollectGarbage()",1);

}

 

I set the form up so the default input should be in the cell of the

first row and second column.

 

<FORM NAME="frm">

  <INPUT TYPE="Text" NAME="txt" Value="Some cell text"><BR>

  <INPUT TYPE="Button" VALUE="Put in row 1, column 2" ONCLICK="xlWrite

(1,2)">

</FORM>

 

6.25.3 Where to download old browsers like IE4

 

Need to get a copy of an old or new browser?

Try the browser archive:   http://browsers.evolt.org/

 

6.25.4 How can I read a table cell's content?

 

NN6 and IE4+ allow full DOM access and thereby access to the content of

a TABLE cell by scriping the HTMLTableCellElement and its child nodes.

A cell itself is scriptable by various means:

  - as the

      this

    object in the cells event handlers

  - by IDing it and accessing

      document.all['cellID']

    respectively

      document.getElementById('cellID')

  - through the rows/cells collection of a table element and its rows:

      tableReference.rows[rowIndex].cells[cellIndex]

 

Note however that a cell can contain complex html elements like a

complete table itself so there is at least in NN6 no api call to

manipulate somethink like a cell's value. IE4+ has the innerText and

innerHTML properties which flatten the DOM tree structure contained in

a cell to a string. If you are sure there is a text node in your cell

you can with NN6 access

  cellReference.firstChild.nodeValue

to read the text. The following is an example for that:

 

<HTML>

<HEAD>

<SCRIPT>

function getCellValue (cellOrId) {

  var cell =

    typeof cellOrId == 'string' ?

      (document.all ? document.all[cellOrId] : document.getElementById

(cellOrId)) :

      cellOrId;

  if (document.all)

    return cell.innerText;

  else {

    cell.normalize();

    if (cell.firstChild.nodeType == 3)

      return cell.firstChild.nodeValue;

    else

      return '';

  }

}

</SCRIPT>

</HEAD>

<BODY>

<A HREF="javascript: alert(getCellValue ('aCell')); void 0">

show cell value of cell named aCell

</A>

|

<A HREF="javascript: var table = document.all ?

                       document.all['aTable'] :

                       document.getElementById('aTable');

                     alert(getCellValue(table.rows[2].cells[0]));

                     void 0"

>

show cell value of cell 0 in row 2 (indices starting with 0)

</A>

<BR>

<TABLE ID="aTable" BORDER="1">

<TR>

<TD ONCLICK="alert(getCellValue(this));">

JavaScript.FAQTs.com

</TD>

</TR>

<TR>

<TD ID="aCell">

Kibology

</TD>

</TR>

<TR>

<TD>

Scriptology

</TD>

</TR></TABLE>

</BODY>

</HTML>

 

6.25.5 How do I get the text content of a link?

 

NN4 has a

  text

property for links (A HREF elements) while IE4+ uses the

  innerText

property available for all HTML elements.

So

  var link = document.links[linkIndex];

  var text = document.all ? link.innerText :

             link.text ? link.text : '';

is a cross browser way to access the text content of a link.

 

6.25.6 How can I remove the mark up from an HTML element's content?

 

That is simple with IE4+. You simply set

  elementRef.innerHTML = elementRef.innerText;

as in

 

<SPAN ONCLICK="this.innerHTML = this.innerText">

<B>

Kibology

</B>

for

<FONT SIZE="+2">

all

</FONT>

</SPAN>

 

6.25.7 How to retrieve the HTML of the file that it's in?

 

IE5:

 

  var html = document.documentElement.outerHTML;

 

IE4 only allows the body to be read:

 

  var bodyHTML = document.body.innerHTML;

 

NN4 calling into java:

 

  function fetchURL(url) {

    if ((location.host == '' && url.indexOf(location.protocol) == -1)  

         ||

         url.indexOf(location.host) == -1)

      {

      netscape.security.PrivilegeManager.enablePrivilege

("UniversalConnect");

      }

    var dest = new java.net.URL(url);

    var dis = new java.io.DataInputStream(dest.openStream());

    var res = "";

    while ((line = dis.readLine()) != null) {

      res += line;

      res += java.lang.System.getProperty("line.separator");

    }

    dis.close();

    return res;

  }

 

  //example call

 

  var html = fetchURL(location.href)

 

 

NN6: you can try to generate the HTML source from the document tree, see

http://www.faqts.com/knowledge-base/view.phtml/aid/970/fid/126/lang/en

which emulates innerHTML/outerHTML of IE for NN6

 

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

--- Knud van Eeden - 27 September 2001 - 02:13 -------------------------

 

For example:

 

<HTML>

 <HEAD>

  <TITLE>

  </TITLE>

 </HEAD>

 <BODY

   onLoad='

    var htmlS = document.documentElement.outerHTML;

    alert( htmlS );

   '

 >

 </BODY>

</HTML>

 

---

 

[Internet: see also:

http://www.faqts.com/knowledge_base/view.phtml/aid/5785]

 

---

 

[Internet: see also:

http://www.faqts.com/knowledge_base/view.phtml/aid/11672/fid/613

]

 

---

 

[Internet: see also a similar question at:

http://www.faqts.com/knowledge_base/view.phtml/aid/9072/fid/53]

 


7         Perl

 

7.1      Documentation

www.perldoc.com

7.2      File Extensions

ActivePerl includes Perl for ISAPI, an extension that can speed up web script launching tremendously by using the ISAPI interface.

 

 

"perlis.dll" is Perl for ISAPI, an IIS plug-in that makes Perl CGI faster.  It's designed specifically for IIS.  However, if you are using Apache or some other webserver, use the "perl.exe".

 

7.3      Modules

 

the fundamental unit of reusability

 

All modules have the file extension .pm and if the module name contains double colons, Perl translates the double colons into the OS’s directory separator (e.g. /).

 

7.3.1      Built-in

 

 

7.3.2      Bundled

 

Perl distributions are bundled with a number of standard modules that reside in the lib directory of the Perl distribution.  For example, the IO::SOCKET::INET module resides here:

 

# ls /usr/local/lib/perl5/5.6.1/IO/Socket

./        ../       INET.pm   UNIX.pm

 

7.3.3      Documentation

 

Each module file (.pm) contains POD (Plain Old Documentation) embedded in it along with the actual code.

 

7.3.4      Finding and Downloading

 

Browse http://search.cpan.org

 

 

Enter the name of the module and click the CPAN Search button.

 

 

Click the link that contains the version number of the module (not the link above it that shows the .pm file, which is there just for documentation purposes).

 

 

Click the Download link (pointing to a .tar.gz file).

 

7.3.5      Location

 

Perl looks for modules in each directory listed in the @INC array.

 

7.3.6      Using

 

use module [ list ]

 

A pragma is a compiler directive.  Imports symbols (subroutines and variables) from a module.  If no list of symbols is given, the symbols named in the module’s internal @EXPORT array are used.  If a list is given, the symbols must be named in the module’s @EXPORT or @EXPORT_OK array.  Symbols in the @EXPORT_OK array must explicitly be listed.  The %EXPORT_TAGS hash definee groups of symbols (defined in @EXPORT and @EXPORT_OK) that can be exported/imported.  (See page 303 in “Programming Perl”, 3rd Edition).

 

The $VERSION variable allows a program using the module to specify a minimum version, e.g.:

 

use MyMod 3.14;

 

Can’t use AutoLoader if more than one package in single .pm file.

 

7.4      Objects

 

bless – turns an ordinary referent into an object

 

7.5      Package

 

a namespace, provides fundamental building block upon which higher-level concepts of modules and classes are constructed

 

 

7.6      Ports

7.6.1      Palm OS

As of February 2001, Perl had not be ported to Palm (according to an O’Reilly columnist).

 

Palm OS Emulator (also known as "pose" or "poser", and originally as "copilot") emulates Palm OS-based handhelds at a hardware level.  Latest version: 3.5.2 (April 16, 2002). http://rpmfind.net/linux/RPM/sourceforge/p/po/pose/pose-3.5-2.i386.html

 

pose-perl - Perl modules implementing the RPC parts of the Palm OS debugger protocol,

and Perl scripts which use them to interact with either the Palm OS Emulator

or real Palm OS devices. Latest version: 3.5.2 (April 16, 2002).

 

7.7      Regular Expressions

 

7.7.1      Greedy vs Minimal Matching

 

By default, Perl quantifiers are greedy, meaning they match as much as they possibly can.  To force minimal matching, place a question mark after any quantifier, e.g. /.*?:/

 

7.8      Scoping

 

 

7.9      Sorting

 

7.9.1      Sorting Hashes by Value

 

Hashes may be sorted by value. Often times this can be a very tricky process especially if we are dealing with numbers. With our current example, we have a "5" value for our nickel element. This will cause some problems as if we just sort the hash by value as it is, the nickel value is a "5" instead of "05".

 

We need to edit our hash to and change is the values to floating-point numbers. This way PERL will properly sort our hash by our values as the nickel element will be valued according to a value of "05" instead of "5".

 

sortvalues.pl:

 

#!/usr/bin/perl

 

print "content-type: text/html \n\n";

 

# DEFINE A HASH

%coins = ( "Quarter" , .25,

           "Dime" , .10,

           "Nickel", .05 );

# FOREACH LOOP

foreach $value (sort {$coins{$a} cmp $coins{$b} }

           keys %coins)

{

     print "$value $coins{$value}<br />";

}

 

7.10System Interaction

 

7.10.1 system()

 

Examine return code as follows:

 

 

7.11Switches

 

Switch

Meaning

-00

defines input record separator as blank line

 

7.12Variables

7.12.1 $/ (input record separator)

 

By default, $/ is \n.

 

7.12.2 $. (input record number)

 

When $/ has its default value, $. is the input line number.

 

7.12.3 @INC

 

Array containing list of all directories where Perl modules reside.  Initially consists of the arguments to any –I command-line switches and the PERL5LIB environment variable.  The list of directories can also be expanded with the use lib pragma, e.g.:

 

 use lib “/mypath/libdir/”;

 

7.12.4 Tied Variables

 

The tie operator associates a variable with a class that implements a new set of behaviors.

 

tie VARIABLE, CLASSNAME, LIST;      # binds VARIABLE to CLASSNAME

$object = tied VARIABLE;

 

equivalent to:

 

$object = tie VARIABLE, CLASSNAME, LIST;

 

Tying a variable invokes a constructor of CLASSNAME with arguments LIST.  Once tied, you treat the variable normally, but each access automatically invokes methods on the underlying object.  Methods called by a tied variable have pre-defined names such as FETCH and STORE.

 

7.12.5 Initializing Arrays

 

@regular_array = (

"value 1",

"value 2"

);

 

The following statements are equivalent, though the second one is more readable:

 

    %hash = ( 'key1', 'value1', 'key2', 'value2', 'key3', 'value3' );

 

    %hash = (

        key1 => 'value1',

        key2 => 'value2',

        key3 => 'value3',

    );


8         PHP

 

Hypertext Preprocessor

 

General-purpose scripting language that is especially suited for Web development and can be embedded into HTML

 

http://www.php.net/

 

http://www.phpriot.com – Tutorials

 

Practical PHP Programming – http://www.hudzilla.org/phpbook/index.php

 

8.1      Accessing Remote Web Pages

8.1.1      Snoopy

PHP net client v1.2 (PHP class that acts like a web browser)

http://snoopy.sourceforge.net

 

8.1.2      urlencode

If using fopen to make http requests that contain a querystring, it is advised that you urlencode() your values, else characters like @ can make fopen (or whatever wrapper it is using) throw an error.

 

8.1.3      Authentication (Regular)

If you're using fopen to open a URL that requires authorization, you might need to force a HTTP/1.0 request for it since fopen won't support HTTP/1.1 requests. You can do that by setting your user_agent to one that is known only to support HTTP/1.0 (most webservers will be configured to force HTTP/1.0 for some browsers). Here's what worked for me:

 

<?php

$returned=URLopen("http://$username:$password@example.com");

 

function URLopen($url)

{

       // Fake the browser type

       ini_set('user_agent','MSIE 4\.0b2;');

 

       $dh = fopen("$url",'r');

       $result = fread($dh,8192);                                                                                                                            

       return $result;

}

?>

 

8.1.4      Authentication (Digest)

abesharp at yahoo dot co dot uk

05-Apr-2005 05:12

This function has a basic implementation of HTTP Digest Authentication (as per RFC 2617) to get a file from a web server which requires digest authentication (as opposed to basic authentication - the difference being that, with basic, your password is sent to the server as plain text, whereas with digest, it is hashed with a server-supplied nonce to protect against sniffing and replay attacks).

 

You just supply the host (e.g www.example.com), the name of the file you want (e.g protected_page.html), and the necessary username and password, and the function returns the contents of the protected file (or the error message that the server sends, if you supplied the wrong credentials).

 

If the server only supports a QOP of auth-int (rather then auth) this function won't work, but can be easily modified with reference to the RFC at http://www.ietf.org/rfc/rfc2617.txt

 

<?php

function readHTTPDigestAuthenticatedFile($host,$file,$username,$password)

{

   if (!$fp=fsockopen($host,80, $errno, $errstr, 15))

       return false;

      

   //first do the non-authenticated header so that the server

   //sends back a 401 error containing its nonce and opaque

   $out = "GET /$file HTTP/1.1\r\n";

       $out .= "Host: $host\r\n";

       $out .= "Connection: Close\r\n\r\n";

 

     fwrite($fp, $out);

 

   //read the reply and look for the WWW-Authenticate element

   while (!feof($fp))

   {

       $line=fgets($fp, 512);

      

       if (strpos($line,"WWW-Authenticate:")!==false)

           $authline=trim(substr($line,18));

   }

  

   fclose($fp);

      

   //split up the WWW-Authenticate string to find digest-realm,nonce and opaque values

   //if qop value is presented as a comma-seperated list (e.g auth,auth-int) then it won't be retrieved correctly

   //but that doesn't matter because going to use 'auth' anyway

   $authlinearr=explode(",",$authline);

   $autharr=array();

  

   foreach ($authlinearr as $el)

   {

       $elarr=explode("=",$el);

       //the substr here is used to remove the double quotes from the values

       $autharr[trim($elarr[0])]=substr($elarr[1],1,strlen($elarr[1])-2);

   }

  

   foreach ($autharr as $k=>$v)

       echo("$k ==> $v\r\n");

  

   //these are all the vals required from the server

   $nonce=$autharr['nonce'];

   $opaque=$autharr['opaque'];

   $drealm=$autharr['Digest realm'];

  

   //client nonce can be anything since this authentication session is not going to be persistent

   //likewise for the cookie - just call it MyCookie

   $cnonce="sausages";

  

   //calculate the hashes of A1 and A2 as described in RFC 2617

   $a1="$username:$drealm:$password";$a2="GET:/$file";

   $ha1=md5($a1);$ha2=md5($a2);

  

   //calculate the response hash as described in RFC 2617

   $concat = $ha1.':'.$nonce.':00000001:'.$cnonce.':auth:'.$ha2;

   $response=md5($concat);

  

   //put together the Authorization Request Header

   $out = "GET /$file HTTP/1.1\r\n";

       $out .= "Host: $host\r\n";

   $out .= "Connection: Close\r\n";

   $out .= "Cookie: cookie=MyCookie\r\n";

   $out .= "Authorization: Digest username=\"$username\", realm=\"$drealm\", qop=\"auth\", algorithm=\"MD5\", uri=\"/$file\", nonce=\"$nonce\", nc=00000001, cnonce=\"$cnonce\", opaque=\"$opaque\", response=\"$response\"\r\n\r\n";

  

   if (!$fp=fsockopen($host,80, $errno, $errstr, 15))

       return false;

  

   fwrite($fp, $out);

  

   //read in a string which is the contents of the required file

   while (!feof($fp))

   {

       $str.=fgets($fp, 512);

   }

  

   fclose($fp);

  

   return $str;

}

 

?>

 

8.2      Command Line Invocation

 

Put #!/usr/local/bin/php as the top line in the PHP file.

 

8.3      Design

What you are doing is bad practice. Don't just have one file, have one file for each page. Store all the common sections in one or several files for inclusion where necessary. Use the query string for its correct job, fetching data.

 

8.4      Forms

8.4.1      Auto Submit

 

<script>

function submitit(){

var form = document.change_it_to_your_form_name;

form.submit();

 

}

</SCRIPT>

 

 

call the above function when you want to submit your form

 

 

There is a post_to_host or posttohost function

 

 

8.5      Functions

8.5.1      Defining a function with no parameters

 

function NameOfThisFunction () {

# the open/close parens are required

}

 

8.5.2      Arithmetic

8.5.2.1       float log ( float arg [, float base] )

If the optional base parameter is specified, log() returns logbase arg, otherwise log() returns the natural logarithm of arg.

Note: The base parameter became available with PHP 4.3.0.

As always you can calculate the logarithm in base b of a number n, but using the mathematical identity: logb(n) = log(n)/log(b), where log is the neperian (or natural) logarithm.

 

8.5.2.2       number pow ( number base, number exp )

Returns base raised to the power of exp. If possible, this function will return an integer.

 

If the power cannot be computed, pow() will return FALSE.

 

Example:

<?php

 

var_dump(pow(2, 8)); // int(256)

echo pow(-1, 20); // 1

echo pow(0, 0); // 1

 

echo pow(-1, 5.5); // error

 

?>

 

8.5.3      String

 

strcmp(STRING1, STRING2) returns 0 if they are identical

 

8.6      MySQL

8.6.1      Persistent Connections

 

Normally you do NOT want to use mysql_pconnect.  This function is designed for environments which have a high overhead to connecting to the database.  In a typical MySQL / Apache / PHP environment, Apache will create many child processes which lie in idle waiting for a web request to be assigned to them.  Each of these child processes will open and hold its own MySQL connection.  So if you have a MySQL server which has a limit of 50 connections, but Apache keeps more than 50 child processes running, each of these child processes can hold a connection to your MySQL server, even while they are idle (idle httpd child processes don't lend their MySQL connection to other httpd children, they hold their own).  So even if you only have a few pages which actually connect to MySQL on a busy site, you can run out of connections, with all of them not actually being used.  In general use mysql_connect() for connecting to MySQL unless that connection takes a long time to establish.

 

Be careful using mysql_pconnect. If you are hosting on an ISP, they may frown upon you using multiple persistant mysql connections as this consumes resources for a longer period of time. If your script crashes, your connection can stay open for long periods of time. If there is a loop involved, you could accidently eat up all the available connections. That might be considered abuse by an ISP and you could get in trouble. Try using mysql_connect first instead. 90% of the time, a non-persistant mysql_connect call will do the trick just fine.

 

if you set wait_timeout, and you have high number of connection closed, you need too, set max_connect_errors (in MySQL) http://www.mysql.com/doc/en/Blocked_host.html

 

If you need to close idle persistent connections, set a low wait_timeout in MySQL

 

don't use pconnect in a situation with MySQL running on one host but on multiple ports (a multiple database configuration). the connection pooling algo in php apparently only keys off of the host, username and password but not the port. therefore, if you use the same host, username and password but a different port, you might get a connection that is connected to a different port than the one you asked for.

 

Be warned if you use different parameters for mysql_pconnect() in different scripts on server: PHP can create single persistent connection for every set of parameters in each process up to mysql.max_persistent (PHP directive) per process. So even if you have MaxClients Apache directive set lesser then max_connections MySQL directive, you can easily get Too many connections MySQL error.  If mysql.max_persistent is set to other value than -1 (unlimited, default value), connections over this limit are silently denied, so use it with care.  Solution: For servers with potentially unlimited set of connection parameters, forbid persistent connection with mysql.allow_persistent=Off.

 

8.7      Object Oriented Programming (OOP)

 

PHP v4 OOP is quirky but PHP v5 OOP is already Java- and C#-class OOP

 

PHP5 does have its advantages. Eventually it'll get pushed to the fore front. It's OOP improvements are an order of magnitude greater than PHP4's

 

Its interesting to note that the high points of PHP5 OOP improvements are easily simulated on PHP4. Even type hinting can be simulated with an is_a() call.

 

8.7.1      Encapsulation

PHP v4 does not enforce encapsulation, i.e. you can access internal variables directly (e.g. $some_page->bgcolor = “red”) instead of forcing you to use a method (e.g. $some_page->setbgcolor(“red”)).

 

8.8      Operators

8.8.1      Arithmetic

 

Example

Name

Result

-$a

Negation

Opposite of $a.

$a + $b

Addition

Sum of $a and $b.

$a - $b

Subtraction

Difference of $a and $b.

$a * $b

Multiplication

Product of $a and $b.

$a / $b

Division

Quotient of $a and $b.

$a % $b

Modulus

Remainder of $a divided by $b.

The division operator ("/") returns a float value anytime, even if the two operands are integers (or strings that get converted to integers).

Note: Remainder $a % $b is negative for negative $a.

 

See also Functions -> Arithmetic

 

8.8.2      String

 

Comparison: ==

 

 

See also Functions -> String

 

8.9      Regular Expressions

 

See PHP\Finer points of PHP regular expressions.htm

 

8.9.1      Greedy

 

Regexes in PHP are greedy by default.  To make them “ungreedy”, use the U modifier.

 

8.10Running Shell Commands

putenv("http_proxy=$PROXY_URL:$PROXY_PORT");

$result = shell_exec("wget -q -O - $url");

 

 

 

Warning

If you are going to allow data coming from user input to be passed to the functions below, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.

 

8.10.1 system()

Description

string system ( string $command [, int &$return_var] )

 

system() is just like the C version of the function in that it executes the given command and outputs the result.

 

The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.

 

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

 

Parameters

 

command

The command that will be executed.

 

return_var

If the return_var argument is present, then the return status of the executed command will be written to this variable.

 

 

Return Values

Returns the last line of the command output on success, and FALSE on failure.

 

8.10.2 exec()

Description

string exec ( string $command [, array &$output [, int &$return_var]] )

 

exec() executes the given command.

 

Parameters

 

command

The command that will be executed.

 

output

If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

 

return_var

If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable.

 

 

Return Values

The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

 

To get the output of the executed command, be sure to set and use the output parameter.

 

Examples

 

Example 1986. An exec() example

 

<?php

// outputs the username that owns the running php/httpd process

// (on a system with the "whoami" executable in the path)

echo exec('whoami');

?>

 

8.10.3 passthru()

Description

void passthru ( string $command [, int &$return_var] )

 

The passthru() function is similar to the exec() function in that it executes a command. This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the Content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.

 

Parameters

 

command

The command that will be executed.

 

return_var

If the return_var argument is present, the return status of the Unix command will be placed here.

 

 

Return Values

No value is returned.

 

8.11Sessions

 

A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL. (http://www.php.net/manual/en/ref.session.php)

 

By default, the contents of session variables are serialized and stored in files (one per session ID) in /tmp on the server.

 

SID (string): Constant containing either the session name and session ID in the form of "name=ID" or empty string if session ID was set in an appropriate session cookie. (http://www.php.net/manual/en/ref.session.php)

 

 

The statement:

<?php session_start() ?>

must be the very first line in the .php file, even before <html> or you will get the message “session_start(): Cannot send session cache limiter - headers already sent”

 

8.12Strings and Character Sets

 

http://ca3.php.net/manual/en/language.types.string.php

 

A string is series of characters. In PHP, a character is the same as a byte, that is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some Unicode support.

 

Do not expect to get the code of one character by converting it to integer (as you would do in C for example). Use the functions ord() and chr() to convert between charcodes and characters.

 

8.12.1 Supporting Internationalization (i18n)

 

http://www.phpwact.org/php/i18n/charsets - EXCELLENT

 

PHP <6 uses ISO 8859-1 natively

 

Use the following to force everything into the UTF-8:

 

// Setting the Content-Type header with charset

header('Content-Type: text/html; charset=utf-8');

 

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

 

<form accept-charset="utf-8">

 

The mbstring extension is potentially a magic wand, as it provides a mechanism to override a large number of PHP‘s string functions (see http://www.php.net/mbstring).

 

mail()

mb_send_mail()

strlen()

mb_strlen()

strpos()

mb_strpos()

strrpos()

mb_strrpos()

substr()

mb_substr()

strtolower()

mb_strtolower()

strtoupper()

mb_strtoupper()

substr_count()

mb_substr_count()

ereg()

mb_ereg()

eregi()

mb_eregi()

ereg_replace()

mb_ereg_replace()

eregi_replace()

mb_eregi_replace()

split()

mb_split()

 

Note: mb_strstr() was introduced in PHP v5.

Note: mb_strtolower() doesn’t work.  It converts lower case characters to non-printable characters.

 

PHP’s PCRE (Perl Compatible Reg Ex) extension also has a u modifier that treats pattern strings as UTF-8.

 

8.12.1.1   Checking String Length

 

With single-byte charsets, we can use:

 

if ( strlen($firstname) > 10 ) {

   die($firstname . ' is too long');

}

 

However, with multi-byte charsets, to handle this correctly we have to use PHP’s PCRE (Perl Compatible Reg Ex) extension and the /u pattern modifier. The test then becomes:

 

if ( !preg_match('/^\w{,10}$/u', $firstname) ) {

   die($firstname . ' is too long');

}

 

The u modified turns on additional functionality of PCRE that is incompatible with Perl. Pattern strings are treated as UTF-8.

 

8.12.1.2   Converting upper case and lower case

 

The normal way to convert between upper and lower case is using PHP‘s strtoupper() and strtolower(). The problem is they rely on the current locale, determined by the current locale setting of the server.  This means that if the default “C” locale is used by the server, characters such as umlaut-A (Ä) will not be converted.  This means there is a finite number of characters that you might need to convert from upper to lower case and vice versa.

 

8.12.2 String access and modification by character

 

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array-brackets like $str[42] so think of a string as an array of characters.

 

Note: They may also be accessed using braces like $str{42} for the same purpose. However, using square array-brackets is preferred because the {braces} style is deprecated as of PHP 6.

 

Examples:

 

// Get the first character of a string

$str = 'This is a test.';

$first = $str[0];

 

// Get the third character of a string

$third = $str[2];

 

// Get the last character of a string.

$str = 'This is still a test.';

$last = $str[strlen($str)-1];

 

// Modify the last character of a string

$str = 'Look at the sea';

$str[strlen($str)-1] = 'e';

 

// Alternative method using {} is deprecated as of PHP 6

$third = $str{2};

 

8.12.3 Character Type Functions

 

http://ca3.php.net/manual/en/ref.ctype.php

 

The functions provided by this extension check whether a character or string falls into a certain character class according to the current locale (see also setlocale()).

 

When called with an integer argument these functions behave exactly like their C counterparts from ctype.h. It means that if you pass an integer smaller than 256 it will use the ASCII value of it to see if it fits in the specified range (digits are in 0x30-0x39). If the number is between -128 and -1 inclusive then 256 will be added and the check will be done on that.

 

When called with a string argument they will check every character in the string and will only return TRUE if every character in the string matches the requested criteria. When called with an empty string the result will always be TRUE in PHP < 5.1 and FALSE since 5.1.

 

Passing anything else but a string or integer will return FALSE immediately.

 

It should be noted that ctype functions are always preferred over regular expressions, and even to some equivalent str_* and is_* functions. This is because of the fact that ctype uses a native C library and thus processes significantly faster.

 

ctype_alnum — Check for alphanumeric character(s)

ctype_alpha — Check for alphabetic character(s)

ctype_cntrl — Check for control character(s)

ctype_digit — Check for numeric character(s)

ctype_graph — Check for any printable character(s) except space

ctype_lower — Check for lowercase character(s)

ctype_print — Check for printable character(s)

ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character

ctype_space — Check for whitespace character(s)

ctype_upper — Check for uppercase character(s)

ctype_xdigit — Check for character(s) representing a hexadecimal digit

 

8.12.4 gettext (GNU)

 

http://ca3.php.net/manual/en/ref.gettext.php

 

8.13Variables

8.13.1 PHP

PHP_SELF

full path of script in the URL following the hostname /admin/array-test.php

PHP_AUTH_USER

user name in .htaccess used to access this directory

PHP_AUTH_PW

password in .htaccess used to access this directory

 

 


9         Shells (UNIX)

 

See \usr\data\tech\unix\shells.doc

 


10   Visual Basic

 

Visual Basic (VB) is an event driven programming language and associated development environment from Microsoft for its COM programming model.  A programmer can put together an application using the components provided with Visual Basic itself. Programs written in Visual Basic can also use the Windows API, but doing so requires external function declarations.

 

Visual Basic can create executables (EXE files), ActiveX controls, DLL files, but is primarily used to develop Windows applications and to interface web database systems. Dialog boxes with less functionality (e.g., no maximize/minimize control) can be used to provide pop-up capabilities. Controls provide the basic functionality of the application, while programmers can insert additional logic within the appropriate event handlers.

 

Scripting languages such as VBA and VBScript are syntactically similar to Visual Basic, but perform differently.

 

http://en.wikipedia.org/wiki/Visual_Basic

 

10.1Derivative Languages

 

 

http://en.wikipedia.org/wiki/Visual_Basic

 

 


11   Visual Basic for Applications

 

Alt-F11 displays the VBA GUI in a given application (e.g. Excel, Outlook).

 


12   Visual Basic Scripting

 

12.1Overview

 

http://en.wikipedia.org/wiki/VBScript

 

12.1.1 Description

 

VBScript (short for Visual Basic Scripting Edition) is an Active Scripting language developed by Microsoft. The language's syntax reflects its pedigree as a variation of Microsoft's Visual Basic programming language. VBScript is installed as default in every desktop release of the Windows Operating System (OS) since Windows 98, and may or may not be included with Windows CE depending on the configuration and purpose of the device it is running on. It initially gained support from Windows administrators seeking an automation tool more powerful than the batch language first developed in the late 1970s. A VBScript script must be executed within a host environment, of which there are several provided on a standard install of Microsoft Windows. Additionally, The VBScript hosting environment is embeddable in other programs, through technologies such as the Microsoft Script control (msscript.ocx).

 

12.1.2 History

 

VBScript began as part of the Microsoft Windows Script Technologies, which were targeted at web developers initially and were launched in 1996. Over a period a little over two years, the VBScript and JScript languages advanced from version 1.0 to 5.0 and over that time system administrators noticed it and began using it. In 5.0, VBScript received a large boost of power with new functionality such as Regular Expressions, Classes, the With statement, Eval/Execute/ExecuteGlobal functions to evaluate and execute script commands built during the execution of another script, a function-pointer system via GetRef(), and Distributed COM (DCOM) support.

 

In 5.5, "Submatches" were added to the regular expression class in VBScript to finally allow VBScript script authors to capture the text within the expression's groups. That capability before was only possible through the JScript member of the Microsoft ActiveX Scripting family.

 

12.1.3 Uses

 

When employed in Microsoft Internet Explorer, VBScript is similar in function to JavaScript, as a language to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page, to perform tasks not possible in HTML alone. Other web browsers such as Firefox, and Opera do not have built-in support for VBScript. This means that where client-side script is required on a web site, developers almost always use JavaScript for cross-browser compatibility.

 

Besides client-side web development, VBScript is used for server-side processing of web pages, most notably with Microsoft Active Server Pages (ASP). The ASP engine and type library, asp.dll, invokes vbscript.dll to run VBScript scripts. VBScript that is embedded in an ASP page is contained within <% and %> context switches. The following example of an ASP page with VBScript displays the current time in military format (Note that an '=' sign occuring after a context switch (<%) is short-hand for a call to Write() method of the Response object).

 

VBScript can also be used to create applications that run directly on a person's computer running Microsoft Windows. One way is through a combination of VBScript and HTML called an HTML Application (file extension .hta). In an HTA, HTML is used for the user interface, and a scripting language such as VBScript is used for the program logic.

 

VBScript is also used when scripts to be executed within the Windows Script Host (WSH) environment. Such a script is usually in a stand-alone file with the file extension .vbs. The script can be invoked in two ways. Wscript.exe is used to display output and receive input in through a GUI, such as dialog and input boxes. Cscript.exe is used in a command-line environment.

 

12.1.4 Functionality

 

As-is, VBScript provides basic date/time, string manipulation, math, user interaction, error handling, and regular expressions. Additional functionality can be added through the use of ActiveX technologies. File system management, file modification, and streaming text operations can be acheived with the Scripting Runtime Library scrrun.dll. Binary file and memory I/O is provided by the "ADODB.Stream" class, which can also be used as a string builder (since a high amount of VBScript string concatenation is costly due to constant memory re-allocation), and can be used to convert an array of bytes to a string and vice versa. Database access is made possible through ActiveX Data Objects (ADO), and the IIS Metabase can be manipulated using the GetObject() function /w sufficient permissions (useful for creating and destroying sites and virtual directories). Additionally, XML files and schemas can be manipulated with the Microsoft XML Library APIs (msxml6.dll, msxml3.dll), which also can be used to retrieve content from the World Wide Web via the XMLHTTP and ServerXMLHTTP objects (class strings "MSXML2.XMLHTTP.6.0" and "MSXML2.ServerXMLHTTP.6.0").

 

12.2Documentation

12.2.1 Tutorials

 

http://www.microsoft.com/technet/scriptcenter/hubs/start.mspx

 

http://www.w3schools.com/vbscript/default.asp

 

12.2.2 Microsoft

 

MSDN Scripting Main page

http://msdn2.microsoft.com/en-us/library/ms950396.aspx

 

Visual Basic Scripting Edition main page:

http://msdn2.microsoft.com/en-us/library/t0aew7h6.aspx

 

http://www.microsoft.com/technet/scriptcenter/guide/default.mspx?mfr=true

 

The Microsoft Windows 2000 Scripting Guide provides a comprehensive overview of the scripting technologies included in the Microsoft Windows 2000 operating systems. This guide is designed to teach you basic concepts underlying Microsoft scripting technologies such as Microsoft Visual Basic Scripting Edition (VBScript), Windows Script Host (WSH), Active Directory Service Interfaces (ADSI), and Windows Management Instrumentation (WMI).

 

12.3Comments

 

Everything after a single quote (‘) character on a line are ignored.

 

12.4Case Insensitivity

 

VBScript is case insensitive.

 

12.5Running VBScripts

 

Cscript is what’s called a script host. The script host is what enables your script to run on the computer. It identifies the scripting language, tracks down the objects requested by the script, and, in general, interprets what’s happening in your script and ensures the computer will understand it. Cscript and Wscript are the two script hosts within the Windows Script Host (WSH) environment.  Unless you specify otherwise, Wscript is the default. When you type the name of a file that ends with a .vbs file extension at a command prompt, Windows automatically uses Wscript to run the script.

 

The difference between Cscript and Wscript is that Cscript is the command-line version of the script host and Wscript is the graphical version. This difference isn’t really noticeable unless your script uses the Wscript.Echo command.

 

12.5.1 cscript

 

From a command prompt, type “cscript test.vbs”.

 

12.5.2 wscript

 

wscript is the program that executes a VBscript when you double click on a .vbs file from Windows Explorer.

 

12.5.3 Setting the Default Script Host

 

You might find that you’re running the majority, if not all, of your scripts with cscript. If that’s the case you might want to change your default script host. To do that you type this at the command prompt:

 

cscript //H:cscript

 

After running this command, if you type only the name of the script file at the command prompt, the script will run under Cscript rather than Wscript (because CScript is now the default script host). To set the default back to Wscript, simply run this command:

 

wscript //H:wscript

 

Of course, even if you’ve changed your default to Cscript, you can still run scripts under Wscript. Simply precede the filename with wscript:

 

wscript test.vbs

 

12.6Input and Output

 

If you use the MsgBox function a message box will display whether you’re running under Cscript or Wscript; the same is true of the InputBox function.

 

12.7Procedures

 

Sub and Function procedure names cannot have a hyphen in them, but they can have an underscore.

 

12.7.1 Sub Procedures

A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value. A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses ().

 

The following Sub procedure uses two intrinsic, or built-in, VBScript functions, MsgBox and InputBox, to prompt a user for information. It then displays the results of a calculation based on that information. The calculation is performed in a Function procedure created using VBScript.

 

Sub ConvertTemp()

 

   temp = InputBox("Please enter the temperature in degrees F.", 1)

 

   MsgBox "The temperature is " & Celsius(temp) & " degrees C."

 

End Sub

 

12.7.2 Function Procedures

 

A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but can also return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant.

 

In the following example, the Celsius function calculates degrees Celsius from degrees Fahrenheit. When the function is called from the ConvertTemp Sub procedure, a variable containing the argument value is passed to the function. The result of the calculation is returned to the calling procedure and displayed in a message box.

 

Sub ConvertTemp()

 

   temp = InputBox("Please enter the temperature in degrees F.", 1)

 

   MsgBox "The temperature is " & Celsius(temp) & " degrees C."

 

End Sub

 

Function Celsius(fDegrees)

 

   Celsius = (fDegrees - 32) * 5 / 9

 

End Function

 

12.7.3 Getting Data into and out of Procedures

 

Each piece of data is passed into your procedures using an argument. Arguments serve as placeholders for the data you want to pass into your procedure. You can name your arguments any valid variable name. When you create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure. Any arguments are placed inside these parentheses, separated by commas. For example, in the following example, fDegrees is a placeholder for the value being passed into the Celsius function for conversion.

 

To get data out of a procedure, you must use a Function. Remember, a Function procedure can return a value; a Sub procedure can't.

 

12.7.4 Using Sub and Function Procedures in Code

 

A Function in your code must always be used on the right side of a variable assignment or in an expression. For example:

 

Temp = Celsius(fDegrees)

-or-

MsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."

 

To call a Sub procedure from another procedure, type the name of the procedure along with values for any required arguments, each separated by a comma. The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses.

 

The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing.

 

Call MyProc(firstarg, secondarg)

 

MyProc firstarg, secondarg

 

Notice that the parentheses are omitted in the call when the Call statement isn't used.

 

12.8Operators

 

12.8.1 String Concatenation (&)

 

12.9HTML Applications (HTAs)

 

http://www.microsoft.com/technet/scriptcenter/hubs/htas.mspx

 

http://www.microsoft.com/technet/scriptcenter/topics/htas/tutorial1.mspx

 

You might expect the Microsoft scripting technologies – such as Windows Script Host (WSH) and VBScript – to have some of the coolest and fanciest graphical user widgets around. Oddly enough, though, that isn’t the case. Outside of a message box here and an input box there, neither WSH nor VBScript offers much in the way of GUI elements. Using WSH and/or VBScript, can you create a form that enables you to select computer names from a list box? No. Can you create a form that allows people to select options from a series of check boxes? No. Can you – sorry; no. If you want a graphical user interface, you’re simply going to have to give up scripting and turn to full-fledged, full-time programming.

 

12.10                        Q and A

 

12.10.1                     Sometimes in VBScript I get errors if I don't use parentheses around function arguments and other times I get the error "can't use parentheses when calling a subroutine" when I *do* use them. What's the problem?

 

Part of what is going on is VBScript distinguishing between different kinds of procedures (Sub or Function). Whether there is a return value being part of that distinction. The upshot is this: You will need parentheses if you are calling a function that returns a value and you are using the return value, or if you are using the 'Call' keyword. For example:

 

' Parentheses can't be used here. Disregarded return value

' makes this a subroutine call.

crt.screen.WaitForString "string", 5

 

' Parentheses needed here. Return value makes this a

' function call.

Dim result

result = crt.screen.WaitForString("string", 5)

 

' Parentheses are always needed when using 'Call'

Call crt.screen.WaitForString("string")

Call crt.screen.WaitForString("string", 5)

 

' With one argument both of these forms are legal.

crt.screen.WaitForString "string"

crt.screen.WaitForString("string")

 


13   Windows Programming

 

13.1Terms

 

DDE - Dynamic Data Exchange; old method of communicating between Windows apps

OLE - Object Linking and Embedding; "DDE that works"; implemented via DLLs (Dynamic Link Library; small executable)

            embedding - client copies info from server program

            linking - client notes file name of server's data

MAPI – Mail API

TAPI – Telephone API

SOAP - Simple Object Access Protocol; SOAP provides an implementation-independent infrastructure (that is you don't need to be running any vendor's operating system to communicate via SOAP) for calling remote objects via HTTP.

 

component-based programming

COM – Component Object Model

ISAPI application - ?

 

A Windows script (*.wsf) file is a text document containing Extensible Markup Language (XML) code. It incorporates several features that offer you increased scripting flexibility. Because Windows script files are not engine-specific, they can contain script from any Windows Script compatible scripting engine. They act as a container.

 

13.2Active Directory Service Interfaces (ADSI)

 

Active Directory Service Interfaces (ADSI) is a set of COM interfaces used to access the features of directory services from different network providers. ADSI is used in a distributed computing environment to present a single set of directory service interfaces for managing network resources. Administrators and developers can use ADSI services to enumerate and manage the resources in a directory service, no matter which network environment contains the resource.

 

ADSI enables common administrative tasks, such as adding new users, managing printers, and locating resources in a distributed computing environment.

 

13.3ActiveX

 

ActiveX scripting architecture enables powerful scripting, using languages such as VBScript and JScript.  (ActiveX scripting engines for Perl, REXX and Python are available from third party vendors.)  Microsoft currently provides three hosts for running these scripting languages across the Windows platform:

·        Internet Explorer

·        Internet Information Server (IIS)

·        Windows Script Host (WSH)

 

Internet Explorer enables scripts to be executed on client computers from within HTML pages.

Internet Information Server now supports Active Server Pages, which enables scripts to be run on Web servers; in other words, it enables server-side scripting over the Internet or an intranet.

Windows Script Host enables scripts to be executed directly on the Windows desktop or command console, without the need to embed those scripts in an HTML document. Scripts can be run directly from the desktop by clicking on a script file, or from the command console. WSH provides a low-memory scripting host that is ideal for non-interactive scripting needs, such as logon scripting, administrative scripting, and so on.

 

www.activex.com

 

Technology developed by Microsoft to add interactive to web pages.  Based on older MS Windows OLE and COM standards.  A mechanism for extending a variety of programming languages

 

Definitions:

 

requires use of IE or ActiveX plug-in for Netscape

 

security rests on “authenticode” scheme for identifying authors of ActiveX controls

 

Java Virtual Machine = code that enables any ActiveX-supported browser (e.g. IE) to run Java applets and to integrate Java applets with ActiveX controls

 

Microsoft Transaction Server (MTS), which is included in the Windows NT Option pack, reduces the complexity and cost of building applications on the server. MTS handles the complexities of developing secure, scalable, and reliable Web applications.

 

13.3.1 How to Run a Program in a Script

 

You cannot run programs directly in an ActiveX script however if you have Microsoft's Windows Script Host (WSH) installed you can tell WSH to run it for you.

 

The following VBScript statements use WSH to start Internet Explorer with a command-line argument:

 

Dim shell

Set shell = CreateObject("WScript.Shell")

shell.Run """C:\Program Files\Internet Explorer\IExplore.exe""http://www.vandyke.com"

 

Here's the same thing in JScript:

 

var shell = new ActiveXObject("WScript.Shell");

shell.Run("\"C:\\Program Files\\Internet Explorer\\IExplore.exe\"http://www.vandyke.com");

 

Note, the Run() function uses whitespace to separate program names from possible command-line arguments. In order to deal with paths with spaces it is necessary to add extra quotes in both languages to make it clear.

 

For information and downloads related to WSH look for the "Windows Script Host" section at:

 

http://msdn.microsoft.com/scripting

 

13.4Active Server Pages

 

Web server does all the script processing, transmitting standard HTML to the browser

 

13.5DirectX

 

suite of multimedia APIs: graphics, sound and music, networking, video

first introduced in 1995; standard for multimedia application development on Windows

 

www.microsoft.com/directx

 

13.6DOS Batch

 

@echo off

 

rem   File: example-dosbatch.bat

rem Author: Darin Davis

rem   Date: 26 July 1997

rem Update: 8 June 2004

rem   Desc: Examples of DOS batch file syntax.

 

 

rem ###################################################################

 

rem   ### COMMENTS ###

rem

rem   Everything after a REM is ignored

rem

rem   To suppress "local echo" of individual batch statments, prepend '@'

rem   before the statement.  To suppress "local echo" globally,

rem   use the "@echo off" command.

 

rem   To print a blank line, put a period after the echo command, e.g.:

echo.

rem ###################################################################

 

rem   ### POSITIONAL PARAMETERS ###

 

                              rem You can specify up to nine

                              rem command line parms (zeroth

                              rem parm is the batch file name).

echo "Cmd line parms are: %0 %1 %2 %3 %4 %5 %6 %7 %8 %9"

 

                              rem pops first arg off list

                              rem (just like Perl operator)

rem shift

 

 

rem ###################################################################

 

 

rem   ### Variables ###

 

                              rem sets FOO's value in the

                              rem environment, which persists

                              rem after this batch file terminates

set FOO="hello world"

 

                              rem prints "hello world"

echo %FOO%

 

 

rem   ### SPECIAL VARIABLES ###

 

                              rem errorlevel is a built-in env

                              rem variable (similiar to the UNIX

                              rem $?) containing the error code

                              rem of the last command executed.

                              rem "errorlevel X" evals to TRUE

                              rem if last exit code >= X.

 

                              rem You can define an arbitrary

                              rem value for errorlevel just like

                              rem any other variable.

dir \junkfile

if errorlevel 1 echo "dir of \junkfile returned errorlevel = %errorlevel%"

 

dir \autoexec.bat

if errorlevel 1 echo "dir of \autoexec.bat returned errorlevel = %errorlevel%"

 

 

 

rem ###################################################################

 

rem   ### CONDITIONS ###

 

                              rem entire if statement must be

                              rem on a single line

if %FOO% == "hello world" echo "FOO has correct value"

 

if not exist \junkfile echo "\junkfile does not exist"

 

 

 

rem ###################################################################

 

rem   ### SUBROUTINES ###

 

                              rem returns to this batch file

                              rem after 'batch_file' exits

rem call batch_file

 

 

rem ###################################################################

 

rem   ### ITERATION ###

 

                              rem BAR must be defined before

                              rem it can be referenced

set BAR=""

 

:firstlabel

echo testing BAR for a value

 

if not %BAR% == %FOO% goto secondlabel

goto thirdlabel

 

:secondlabel

set BAR=%FOO%

goto firstlabel

 

:thirdlabel

echo BAR = %BAR%

 

13.7Windows Management Instrumentation (WMI)

 

Windows Management Instrumentation (WMI) is a component of the Microsoft® Windows® operating system and is the Microsoft implementation of Web-Based Enterprise Management (WBEM), which is an industry initiative to develop a standard technology for accessing management information in an enterprise environment. WMI offers a variety of programming interfaces such as C++, open database connectivity (ODBC), Microsoft® Visual Basic®, or HTML that developers can use to customize management applications. System administrators can use WMI by using scripts to automate administration tasks. WMI can integrate with Windows components, such as Active Directory® directory service to allow for a unified management experience.

 

 

Windows Management Instrumentation (WMI).

Note: WMI is a powerful, sophisticated technology based on Web Based Enterprise Management (WBEM). WMI is primarily used for accessing and instrumenting management information in an enterprise environment. For more information on WMI, see Microsoft Windows Management Instrumentation: Background and Overview at (http://msdn.microsoft.com/library/default.asp?URL=/library/backgrnd/html/wmixwdm.htm).

 

 

13.8Windows Scripting Host (WSH)

 

http://msdn2.microsoft.com/en-us/library/shzd7dy4.aspx

 

What Is WSH?

 

Windows Script Host (WSH) is a Windows administration tool.

 

WSH creates an environment for hosting scripts. That is, when a script arrives at your computer, WSH plays the part of the host — it makes objects and services available for the script and provides a set of guidelines within which the script is executed. Among other things, Windows Script Host manages security and invokes the appropriate script engine.

 

WSH is language-independent for WSH-compliant scripting engines. It brings simple, powerful, and flexible scripting to the Windows platform, allowing you to run scripts from both the Windows desktop and the command prompt.

 

Windows Script Host is ideal for noninteractive scripting needs, such as logon scripting, administrative scripting, and machine automation.

 


14   UNIX Programming

 

14.1Common cc Compiler Options

 

Name of output file:                  -o output_filename

Compile only (don't link)           -c

Optimize                                   -O (mutually exclusive of -g)

Generate debug info                  -g (mutually exclusive of -O)

Link with library                        -l library_name

Additional include file path        -I dir

Additional library path               -L dir

Strip symbol info from               -s (this a a linker, ld, option)

            executable

 

14.2Environment Variables

 

The –m flag of gcc specifies Machine-specific options, in this case 32/64-bit compilation:

 

# setenv CFLAGS "-m64"
# setenv LDFLAGS "-mcpu=v9 -m64"

 

LD_LIBRARY_PATH is an environment variable you set to give the run-time shared library loader (ld.so) an extra set of directories to look for when searching for shared libraries. Multiple directories can be listed, separated with a colon (:). This list is prepended to the existing list of compiled-in loader paths for a given executable, and any system default loader paths.

 

14.3Include/Header files

 

Include/header files contain C source code statements.  They are included in main C programs for the compiler to compile.  You must explicitly include any header files you need; no header files are automatically included.

 

The default include path is /usr/include.  #include statements using angle brackets (<stdio.h>) indicate that the header file is in the default include path.  #include statements using double quotes ("example.h") specify the complete path to the header file.

 

If you want to use all angle brackets in your source file, you must specify an additional include file path when you compile.  For example, if you want to change the source statement:

 

            #include "example.h"     /* located in current directory */

            #include "myheader.h"   /* located in $HOME/include    */

to

            #include <example.h>

            #include <myheader.h>

 

you will have to use the -I flag when you compile:

 

            cc -I . -I $HOME/include -o example example.c

 

To specify C include files or C declarations in a C++ source file, the statement must be enclosed in the following structure:

 

   extern "C" {

     statement

     ...

     statement

   }

 

14.4Libraries

 

Libraries are "modules" of compiled C code that are linked to other compiled C code "modules".  By default, the standard C library is linked to any main program you compile; you must explicitly link any other library you need.  For example, if you want to link to the C math library, you would use the syntax:

 

      cc -o example example.c -lm

 

The default library path is /usr/lib.  Libraries are named by prefixing the letters "lib" and postfixing the letters ".a".  For example, the standard C library's name is "libc.a".  If you want to link to a library not in the default path, you must specify an additional path, for example:

 

      cc -L $HOME/lib -o example example.c -lmylib

 

where mylib is the file $HOME/lib/libmylib.a.

 

Alternatively, add the path to the LD_LIBRARY_PATH environment variable.

 

14.4.1 How do I create a static (.a) library? How about a shared (.so) library?

 

This depends on the compiler you are using. In order to create a static library, you first need to compile all of your source code files (i.e. create a bunch of .o files). Once this is done, you can create a library with the command:

 

     ar -ru libfoo.a *.o

 

Creating a shared library is a bit more complicated. All of the source code files must be compiled as postition independant code. Compilers have an option to do this, but it varies from compiler to compiler. On Solaris, using cc/CC/f77, use the -KPIC option (or perhaps the -Kpic option... read the man page for the appropriate compiler for details). With gcc/g++, use -fPIC or -fpic. On Irix using cc/CC/f77, use -KPIC. For example, on solaris, you might use the command:

 

     cc -KPIC -c junk.c

 

Once all the .o files are created, they must be linked to form a shared library. Use the same compiler you used to compile all of the source files (assuming that you are not mixing computer languages; if you are mixing languages, you may need additional options, but you will have to determine that yourself). Each compiler has an option to tell the compiler to create a shared library. On Solaris using cc/CC/f77, it is -G. On Irix and with gcc/g++, it is -shared. So, on solaris, you might use the command:

     cc -KPIC -G -o libfoo.so *.o

 

14.5Make

 

14.5.1 Rules

 

Character

Description

-

ignores non-zero error codes returned by a command (which would otherwise cause make to stop processing)

@

suppresses displaying the command before executing it

 

14.5.2 Debugging

 

The –d flag displays the reasons why make chooses to rebuild a target.

 

14.5.3 Command line options

 

Re: Using gcc to build Tk-perl

 

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

 

From: Nick Ing-Simmons <nik@tiuk.ti.com>

To: nnylfv@ny.ubs.com

Cc: ptk@lists.Stanford.EDU

Date: Tue, 15 Oct 1996 08:39:22 +0100

Message-Id: <199610150739.IAA08722@pluto>

 

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

 

Olivier Lefevre <nnylfv@ny.ubs.com> writes:

>I have my CC env. variable set to gcc, yet your configuration procedure

>picks cc as the compiler. Furthermore, it appears that there is no way

>to force it to use gcc

 

>Please explain me how to use gcc and consider reading

>the CC env. variable and observing its value.

 

Basing a package compile on environment variables is risky, there is

no telling what they mean to the user that set them. (I have seen CC

used as a default copy list for outgoing mail...)

 

perl/Tk uses same C compiler as was used to build perl.

 

This is very important on some platforms where different compilers use different

calling conventions.

 

For SunOS5 'cc' and 'gcc' need different command line args to build dynamically

loaded objects. Thus _one_ environment variable is insufficient to switch

compilers. It would need to vary for different steps as follows:

 

cc                   gcc            # root exectutable compile

cc -K pic            gcc -fpic      # small modules compile

cc -K PIC            gcc -fPIC      # big modules compile

cc -L/usr/local/lib  gcc            # Link step (extra -L to gcc is harmless)

 

Perl's Configure and perl/Tk's Makefile.PL handle all this, but need

to know which compiler they are using...

 

>(there is no reference to a CC variable in

>Makefile.PL).

 

But there is in the generated Makefile.

Use if very carefully from the command line, being sure to specify

the other variables necessary as well:

 

make CC=gcc CCCDLFLAGS=-fPIC LDDLFLAGS="-G -L/usr/local/lib" \

     LDFLAGS="-L/usr/local/lib"

 

To use gcc the easy way, re-configure perl to use gcc:

 

cd perl5.003

make distclean  # if built before

./Configure -des -Dcc=gcc

make

make install

cd Tk400.200

make clean      # if built before

perl Makefile.PL

make

make install

 

>

>Thank you very much

>

>Olivier Lefevre

>Union Bank of Switzerland

>New York

>

>     2/ I tried to e-mail to ptk@guest.wpi.edu first but it bounced

 

New address (as in Tk400.200 README is ptk@lists.Stanford.EDU).

 

14.5.4 Example makefile

 

# boilerplate Makefile

# Assign the executable's name to PROGNAME, supply a space-separated

# list of object files as OBJS, and set the CFLAGS and LIBS variables

# to reflect the options you want passed to the C compiler and linker,

# respectively.

 

PROGNAME=example1

OBJS=example1.o

CFLAGS=-O -I .

LIBS=-s

 

all:        ${PROGNAME}

 

${PROGNAME}:        ${OBJS}

            cc ${LIBS} ${OBJS} -o ${PROGNAME}

 

clean:

            rm -f ${OBJS} ${PROGNAME}

 

14.6How to use Imakefiles

 

1 - export PATH=$PATH:/usr/lpp/X11/Xamples/config

    (this is the path to the imake executable)

2 - cd into the directory which has the Imakefile

3 - /usr/lpp/X11/Xamples/util/scripts/ximake.sh /usr/lpp/X11/Xamples

    (the ximake.sh script uses the imake executable to create a Makefile)

4 - make

 

(Got this information from "UNIX Program Development for IBM PCs" by Thomas Yager, Addison-Wesley, 1991, ISBN 0-201-57727-5)

 

14.7Lint

 

Two useful flags:

 

-u         Suppresses messages about functions and external variables that are

            either used and not defined or defined and not used.

 

-x         suppress messages about variables that have external declarations

            but are never used

 

14.8Debugging with truss

 

“The truss utility executes the specified command and produces a trace of the system calls it performs, the signals it receives, and the machine faults it incurs.”

 

The following subsections are from the Solaris 2.8 man pages.

 

14.8.1 close()

 

The close() function will deallocate  the  file  descriptor indicated  by  fildes.  To deallocate means to make the file descriptor available  for  return  by  subsequent  calls  to open(2)  or  other functions that allocate file descriptors.  All outstanding record locks owned by  the  process  on  the file  associated  with  the  file descriptor will be removed (that is, unlocked).

 

Upon successful completion, 0 is returned. Otherwise, -1  is returned and errno is set to indicate the error.

 

The close() function will fail if:

 

EBADF

The fildes argument is not a valid file descriptor.

EINTR

The close() function was interrupted by a signal.

ENOLINK

The fildes argument is on a  remote  machine  and  the link to that machine is no longer active.

ENOSPC

There was no free space remaining on the  device  containing the file.

 

The close() function may fail if:

 

EIO

An I/O error occurred while reading from or writing to the file system.

 

14.8.2 ioctl()

 

The ioctl() function performs a variety of control functions on devices and STREAMS. For non-STREAMS files, the functions performed by this call are device-specific control functions.

 

Upon successful completion, the value returned depends  upon the  device  control  function,  but  must be a non-negative integer.  Otherwise, -1 is returned  and  errno  is  set  to indicate the error.

 

The ioctl() function will fail for any type of file if:

 

EBADF

The fildes argument is not a valid open file descriptor.

EINTR

A signal was caught during the execution of the ioctl() function.

EINVAL

The STREAM or  multiplexer  referenced  by  fildes  is linked (directly or indirectly) downstream from a multiplexer.

 

The ioctl() function will also fail  if  the  device  driver detects an error.  In this case, the error is passed through ioctl() without change to the caller.  A particular driver might not have all of the following error cases. Under the following conditions, requests to device drivers may fail and set errno to indicate the error.

 

EFAULT

The request argument requires a data transfer to or from a buffer pointed to by arg, but arg points to an illegal address.

EINVAL

The request or arg argument is not valid for this device.

EIO

Some physical I/O error has occurred.

ENOLINK

The fildes argument is on a remote machine and the link to that machine is no longer active.

ENOTTY

The fildes argument is not associated with a STREAMS device that accepts control functions.

ENXIO

The request and arg arguments are valid for this device driver, but the service requested cannot be performed on this particular subdevice.

ENODEV

The fildes argument refers to a valid STREAMS device, but the corresponding device driver does not support the ioctl() function.

 

STREAMS errors are described in streamio(7I).

 

14.8.3 mmap()

 

The mmap() function establishes a mapping between a process's address space and a file or shared memory object.

 

14.8.4 open()

 

The open() function establishes  the  connection  between  a file and a file descriptor. It creates an open file description that refers to a file and a file descriptor that refers to that open file description. The file descriptor is used by other I/O functions to refer to that file.   The path argument points to a pathname naming the file.

 

The open() function returns a file descriptor for the  named file that is the lowest file descriptor not currently open for that process. The open file description is new, and therefore the file descriptor does not share it with any other process in the system.

 

The open() function will fail if:

 

EACCES

Search permission is denied on a component of the path prefix,  or the file exists and the permissions speci- fied by oflag are denied, or the file does  not  exist and  write  permission is denied for the parent direc- tory of the file to be created, or O_TRUNC  is  speci- fied and write permission is denied.

EDQUOT

The file does not exist,  O_CREAT  is  specified,  and either the directory where the new file entry is being placed cannot be extended because the user's quota  of disk blocks on that file system has been exhausted, or the user's quota of inodes on the  file  system  where the file is being created has been exhausted.

EEXIST

The O_CREAT and O_EXCL flags are set,  and  the  named file exists.

EINTR

A signal was caught during open().

EFAULT

The path argument points to an illegal address.

EIO

The path argument names a STREAMS file and a hangup or error occurred during the open().

EISDIR

The named file  is  a  directory  and  oflag  includes O_WRONLY or O_RDWR.

ELOOP

Too many symbolic links were encountered in  resolving path.

EMFILE

OPEN_MAX file descriptors are currently  open  in  the calling process.

EMULTIHOP

Components of path require hopping to multiple  remote machines and the file system does not allow it.

ENAMETOOLONG

The length of the path argument exceeds PATH_MAX or  a pathname component is longer than NAME_MAX.

ENFILE