Asp Tutorial

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Asp Tutorial as PDF for free.

More details

  • Words: 21,818
  • Pages: 74
XML TUTORIAL What is XML?

   o

So XML is Just Like HTML? So XML Is Just Like SGML?

Why XML?

 o o

What's a Document?

XML Development Goals

How Is XML Defined? Understanding the Specs

What Do XML Documents Look Like?

      

Elements

 

Well-formed Documents

Entity References Comments Processing Instructions CDATA Sections Document Type Declarations Other Markup Issues

Validity

Valid Documents

Pulling the Pieces Together

   

Simple Links Extended Links Extended Pointers Extended Link Group

o

Understanding The Pieces

o o

Style and Substance Conclusion

What is XML? XML is a markup language for documents containing structured information. Structured information contains both content (words, pictures, etc.) and some indication of what role that content plays (for example, content in a section heading has a different meaning from content in a footnote, which means something different than content in a figure caption or content in a database table, etc.). Almost all documents have some structure. A markup language is a mechanism to identify structures in a document. The XML specification defines a standard way to add markup to documents.

What's a Document? The number of applications currently being developed that are based on, or make use of, XML documents is truly amazing (particularly when you consider that XML is not yet a year old)! For our purposes, the word "document" refers not only to traditional documents, like this one, but also to the miriad of other XML "data formats". These include vector graphics, e-commerce transactions, mathematical equations, object meta-data, server APIs, and a thousand other kinds of structured information.

So XML is Just Like HTML? No. In HTML, both the tag semantics and the tag set are fixed. An

is always a first level heading and the tag is meaningless. The W3C, in conjunction with browser vendors and the WWW community, is constantly working to extend the definition of HTML to allow new tags to keep pace with changing technology and to bring variations in presentation (stylesheets) to the Web. However, these changes are always rigidly confined by what the browser vendors have implemented and by the fact that backward compatibility is paramount. And for people who want to disseminate information widely, features supported by only the latest releases of Netscape and Internet Explorer are not useful. XML specifies neither semantics nor a tag set. In fact XML is really a meta-language for describing markup languages. In other words, XML provides a facility to define tags and the structural relationships between them. Since there's no predefined tag set, there can't be any preconceived semantics. All of the semantics of an XML document will either be defined by the applications that process them or by stylesheets.

So XML Is Just Like SGML? No. Well, yes, sort of. XML is defined as an application profile of SGML. SGML is the Standard Generalized Markup Language defined by ISO 8879. SGML has been the standard, vendor-independent way to maintain repositories of structured documentation for more than a decade, but it is not well suited to serving documents over the web (for a number of technical reasons beyond the scope of this article). Defining XML as an application profile of SGML means that any fully conformant SGML system will be able to read XML documents. However, using and understanding XML documents does not require a system that is capable of understanding the full generality of SGML. XML is, roughly speaking, a restricted form of SGML. For technical purists, it's important to note that there may also be subtle differences between documents as understood by XML systems and those same documents as understood by SGML systems. In particular, treatment of white space immediately adjacent to tags may be different.

Why XML? In order to appreciate XML, it is important to understand why it was created. XML was created so that richly structured documents could be used over the web. The only viable alternatives, HTML and SGML, are not practical for this purpose. HTML, as we've already discussed, comes bound with a set of semantics and does not provide arbitrary structure. SGML provides arbitrary structure, but is too difficult to implement just for a web browser. Full SGML systems solve large, complex problems that justify their expense. Viewing structured documents sent over the web rarely carries such justification. This is not to say that XML can be expected to completely replace SGML. While XML is being designed to deliver structured content over the web, some of the very features it lacks to make this practical, make SGML a more satisfactory solution for the creation and long-time storage of complex documents. In many organizations, filtering SGML to XML will be the standard procedure for web delivery.

XML Development Goals The XML specification sets out the following goals for XML: [Section 1.1] (In this article, citations of the form [Section 1.1], these are references to the W3C Recommendation Extensible Markup Language (XML) 1.0. If you are interested in more technical detail about a particular topic, please consult the specification) 1. 2. 3.

4. 5. 6. 7.

8.

It shall be straightforward to use XML over the Internet. Users must be able to view XML documents as quickly and easily as HTML documents. In practice, this will only be possible when XML browsers are as robust and widely available as HTML browsers, but the principle remains. XML shall support a wide variety of applications. XML should be beneficial to a wide variety of diverse applications: authoring, browsing, content analysis, etc. Although the initial focus is on serving structured documents over the web, it is not meant to narrowly define XML. XML shall be compatible with SGML. Most of the people involved in the XML effort come from organizations that have a large, in some cases staggering, amount of material in SGML. XML was designed pragmatically, to be compatible with existing standards while solving the relatively new problem of sending richly structured documents over the web. It shall be easy to write programs that process XML documents. The colloquial way of expressing this goal while the spec was being developed was that it ought to take about two weeks for a competent computer science graduate student to build a program that can process XML documents. The number of optional features in XML is to be kept to an absolute minimum, ideally zero. Optional features inevitably raise compatibility problems when users want to share documents and sometimes lead to confusion and frustration. XML documents should be human-legible and reasonably clear. If you don't have an XML browser and you've received a hunk of XML from somewhere, you ought to be able to look at it in your favorite text editor and actually figure out what the content means. The XML design should be prepared quickly. Standards efforts are notoriously slow. XML was needed immediately and was developed as quickly as possible.

The design of XML shall be formal and concise. In many ways a corollary to rule 4, it essentially means that XML must be expressed in EBNF and must be amenable to modern compiler tools and techniques. There are a number of technical reasons why the SGML grammar cannot be expressed in EBNF. Writing a proper SGML parser requires handling a variety of rarely used and difficult to parse language features. XML does not. 9. XML documents shall be easy to create. Although there will eventually be sophisticated editors to create and edit XML content, they won't appear immediately. In the interim, it must be possible to create XML documents in other ways: directly in a text editor, with simple shell and Perl scripts, etc. 10. Terseness in XML markup is of minimal importance. Several SGML language features were designed to minimize the amount of typing required to manually key in SGML documents. These features are not

supported in XML. From an abstract point of view, these documents are indistinguishable from their more fully specified forms, but supporting these features adds a considerable burden to the SGML parser (or the person writing it, anyway). In addition, most modern editors offer better facilities to define shortcuts when entering text.

How Is XML Defined? XML is defined by a number of related specifications: Extensible Markup Language (XML) 1.0 Defines the syntax of XML. The XML specification is the primary focus of this article. XML Pointer Language (XPointer) and XML Linking Language (XLink) Defines a standard way to represent links between resources. In addition to simple links, like HTML's tag, XML has mechanisms for links between multiple resources and links between read-only resources. XPointer describes how to address a resource, XLink describes how to associate two or more resources. Extensible Style Language (XSL) Defines the standard stylesheet language for XML. As time goes on, additional requirements will be addressed by other specifications. Currently (Sep, 1998), namespaces (dealing with tags from multiple tag sets), a query language (finding out what's in a document or a collection of documents), and a schema language (describing the relationships between tags, DTDs in XML) are all being actively pursued.

Understanding the Specs For the most part, reading and understanding the XML specifications does not require extensive knowledge of SGML or any of the related technologies. One topic that may be new is the use of EBNF to describe the syntax of XML. Please consult the discussion of EBNF in the appendix of this article for a detailed description of how this grammar works.

What Do XML Documents Look Like? If you are conversant with HTML or SGML, XML documents will look familiar. A simple XML document is presented in Example 1. Example 1. A Simple XML Document

Say goodnight, Gracie. Goodnight, Gracie.

A few things may stand out to you:

• • •

The document begins with a processing instruction: . This is the XML declaration [Section 2.8]. While it is not required, its presence explicitly identifies the document as an XML document and indicates the version of XML to which it was authored. There's no document type declaration. Unlike SGML, XML does not require a document type declaration. However, a document type declaration can be supplied, and some documents will require one in order to be understood unambiguously. Empty elements ( in this example) have a modified syntax [Section 3.1]. While most elements in a document are wrappers around some content, empty elements are simply markers where something occurs (a horizontal rule for HTML's
tag, for example, or a cross reference for DocBook's <xref> tag). The trailing /> in the modified syntax indicates to a program processing the XML document that the element is empty and no matching end-tag should be sought. Since XML documents do not require a document type declaration, without this clue it could be impossible for an XML parser to determine which tags were intentionally empty and which had been left empty by mistake. XML has softened the distinction between elements which are declared as EMPTY and elements which merely have no content. In XML, it is legal to use the empty-element tag syntax in either case. It's also legal to use a start-tag/end-tag pair for empty elements: . If interoperability is of any concern, it's best to reserve empty-element tag syntax for elements which are declared as EMPTY and to only use the empty-element tag form for those elements.

XML documents are composed of markup and content. There are six kinds of markup that can occur in an XML document: elements, entity references, comments, processing instructions, marked sections, and document type declarations. The following sections introduce each of these markup concepts.

Elements Elements are the most common form of markup. Delimited by angle brackets, most elements identify the nature of the content they surround. Some elements may be empty, as seen above, in which case they have no content. If an element is not empty, it begins with a start-tag, <element>, and ends with an end-tag, .

Attributes Attributes are name-value pairs that occur inside start-tags after the element name. For example,



is a div element with the attribute class having the value preface. In XML, all attribute values must be quoted.

Entity References In order to introduce markup into a document, some characters have been reserved to identify the start of markup. The left angle bracket, < , for instance, identifies the beginning of an element start- or end-tag. In order to insert these characters into your document as content, there must be an alternative way to represent them. In XML, entities are used to represent these special characters. Entities are also used to refer to often repeated or varying text and to include the content of external files. Every entity must have a unique name. Defining your own entity names is discussed in the section on entity declarations. In order to use an entity, you simply reference it by name. Entity references begin with the ampersand and end with a semicolon.

For example, the lt entity inserts a literal < into a document. So the string <element> can be represented in an XML document as <element>. A special form of entity reference, called a character reference [Section 4.1], can be used to insert arbitrary Unicode characters into your document. This is a mechanism for inserting characters that cannot be typed directly on your keyboard. Character references take one of two forms: decimal references, ℞, and hexadecimal references, ℞. Both of these refer to character number U+211E from Unicode (which is the standard Rx prescription symbol, in case you were wondering).

Comments Comments begin with . Comments can contain any data except the literal string --. You can place comments between markup anywhere in your document. Comments are not part of the textual content of an XML document. An XML processor is not required to pass them along to an application.

Processing Instructions Processing instructions (PIs) are an escape hatch to provide information to an application. Like comments, they are not textually part of the XML document, but the XML processor is required to pass them to an application. Processing instructions have the form: . The name, called the PI target, identifies the PI to the application. Applications should process only the targets they recognize and ignore all other PIs. Any data that follows the PI target is optional, it is for the application that recognizes the target. The names used in PIs may be declared as notations in order to formally identify them. PI names beginning with xml are reserved for XML standardization.

CDATA Sections In a document, a CDATA section instructs the parser to ignore most markup characters. Consider a source code listing in an XML document. It might contain characters that the XML parser would ordinarily recognize as markup (< and &, for example). In order to prevent this, a CDATA section can be used.

Between the start of the section, , all character data is passed directly to the application, without interpretation. Elements, entity references, comments, and processing instructions are all unrecognized and the characters that comprise them are passed literally to the application. The only string that cannot occur in a CDATA section is ]]>.

Document Type Declarations A large percentage of the XML specification deals with various sorts of declarations that are allowed in XML. If you have experience with SGML, you will recognize these declarations from SGML DTDs (Document Type Definitions). If you have never seen them before, their significance may not be immediately obvious. One of the greatest strengths of XML is that it allows you to create your own tag names. But for any given application, it is probably not meaningful for tags to occur in a completely arbitrary order. Consider the old joke example introduced earlier. Would this be meaningful?

Goodnight, Gracie ,

Say goodnight Gracie.


It's so far outside the bounds of what we normally expect that it's nonsensical. It just doesn't mean anything. However, from a strictly syntactic point of view, there's nothing wrong with that XML document. So, if the document is to have meaning, and certainly if you're writing a stylesheet or application to process it, there must be some constraint on the sequence and nesting of tags. Declarations are where these constraints can be expressed. More generally, declarations allow a document to communicate meta-information to the parser about its content. Meta-information includes the allowed sequence and nesting of tags, attribute values and their types and defaults, the names of external files that may be referenced and whether or not they contain XML, the formats of some external (non-XML) data that may be referenced, and the entities that may be encountered. There are four kinds of declarations in XML: element type declarations, attribute list declarations, entity declarations, and notation declarations.

Element Type Declarations Element type declarations [Section 3.2] identify the names of elements and the nature of their content. A typical element type declaration looks like this:



This declaration identifies the element named oldjoke. Its content model follows the element name. The content model defines what an element may contain. In this case, an oldjoke must contain burns and allen and may contain applause. The commas between element names indicate that they must occur in succession. The plus after burns indicates that it may be repeated more than once but must occur at least once. The question mark after applause indicates that it is optional (it may be absent, or it may occur exactly once). A name with no punctuation, such as allen, must occur exactly once. Declarations for burns, allen, applause and all other elements used in any content model must also be present for an XML processor to check the validity of a document. In addition to element names, the special symbol #PCDATA is reserved to indicate character data. The moniker PCDATA stands for parseable character data .

Elements that contain only other elements are said to have element content [Section 3.2.1]. Elements that contain both other elements and #PCDATA are said to have mixed content [Section 3.2.2]. For example, the definition for burns might be

The vertical bar indicates an or relationship, the asterisk indicates that the content is optional (may occur zero or more times); therefore, by this definition, burns may contain zero or more characters and quote tags, mixed in any order. All mixed content models must have this form: #PCDATA must come first, all of the elements must be separated by vertical bars, and the entire group must be optional. Two other content models are possible: EMPTY indicates that the element has no content (and consequently no endtag), and ANY indicates that any content is allowed. The ANY content model is sometimes useful during document conversion, but should be avoided at almost any cost in a production environment because it disables all content checking in that element. Here is a complete set of element declarations for Example 1: Example 2. Element Declarations for Old Jokes

Attribute List Declarations Attribute list declarations [Section 3.3] identify which elements may have attributes, what attributes they may have, what values the attributes may hold, and what value is the default. A typical attribute list declaration looks like this:



In this example, the oldjoke element has three attributes: name, which is an ID and is required; label, which is a string (character data) and is not required; and status, which must be either funny or notfunny and defaults to funny, if no value is specified. Each attribute in a declaration has three parts: a name, a type, and a default value. You are free to select any name you wish, subject to some slight restrictions [Section 2.3, production 5], but names cannot be repeated on the same element. There are six possible attribute types:

CDATA

CDATA attributes are strings, any text is allowed. Don't confuse CDATA attributes with CDATA sections, they are unrelated.

ID The value of an ID attribute must be a name [Section 2.3, production 5]. All of the ID values used in a document must be different. IDs uniquely identify individual elements in a document. Elements can have only a single ID attribute.

IDREF

or IDREFS An IDREF attribute's value must be the value of a single ID attribute on some element in the document. The value of an IDREFS attribute may contain multiple IDREF values separated by white space [Section 2.3, production 3].

ENTITY or ENTITIES An ENTITY attribute's value must be the name of a single entity (see the discussion of entity declarations below). The value of an ENTITIES attribute may contain multiple entity names separated by white space.

NMTOKEN or NMTOKENS Name token attributes are a restricted form of string attribute. In general, an NMTOKEN attribute must consist of a single word [Section 2.3, production 7], but there are no additional constraints on the word, it doesn't have to match another attribute or declaration. The value of an NMTOKENS attribute may contain multiple NMTOKEN values separated by white space. A list of names You can specify that the value of an attribute must be taken from a specific list of names. This is frequently called an enumerated type because each of the possible values is explicitly enumerated in the declaration. Alternatively, you can specify that the names must match a notation name (see the discussion of notation declarations below). There are four possible default values:

#REQUIRED

The attribute must have an explicitly specified value on every occurrence of the element in the document.

#IMPLIED "value"

The attribute value is not required, and no default value is provided. If a value is not specified, the XML processor must proceed without one. An attribute can be given any legal value as a default. The attribute value is not required on each element in the document, and if it is not present, it will appear to be the specified default.

#FIXED "value"

An attribute declaration may specify that an attribute has a fixed value. In this case, the attribute is not required, but if it occurs, it must have the specified value. If it is not present, it will appear to be the specified default. One use for fixed attributes is to associate semantics with an element. A complete discussion is beyond the scope of this article, but you can find several examples of fixed attributes in the XLink specification. The XML processer performs attribute value normalization [Section 3.3.3] on attribute values: character references are replaced by the referenced character, entity references are resolved (recursively), and whitespace is normalized.

Entity Declarations Entity declarations [Section 4.2] allow you to associate a name with some other fragment of content. That construct can be a chunk of regular text, a chunk of the document type declaration, or a reference to an external file containing either text or binary data. A few typical entity declarations are shown in Example 3.

Example 3. Typical Entity Declarations


ATI "ArborText, Inc.">
SYSTEM

"/standard/legalnotice.xml">

There are three kinds of entities: Internal Entities Internal entities [Section 4.2.1] associate a name with a string of literal text. The first entity in Example 3 is an internal entity. Using &ATI; anywhere in the document will insert ArborText, Inc. at that location. Internal entities allow you to define shortcuts for frequently typed text or text that is expected to change, such as the revision status of a document. Internal entities can include references to other internal entities, but it is an error for them to be recursive. The XML specification predefines five internal entities:

• • • • •

< produces the left angle bracket, < > produces the right angle bracket, > & produces the ampersand, & ' produces a single quote character (an apostrophe), ' " produces a double quote character, "

External Entities External entities [Section 4.2.2] associate a name with the content of another file. External entities allow an XML document to refer to the contents of another file. External entities contain either text or binary data. If they contain text, the content of the external file is inserted at the point of reference and parsed as part of the referring document. Binary data is not parsed and may only be referenced in an attribute. Binary data is used to reference figures and other non-XML content in the document. The second and third entities in Example 3 are external entities. Using &boilerplate; will have insert the contents of the file /standard/legalnotice.xml at the location of the entity reference. The XML processor will parse the content of that file as if it occurred literally at that location. The entity ATIlogo is also an external entity, but its content is binary. The ATIlogo entity can only be used as the value of an ENTITY (or ENTITIES) attribute (on a graphic element, perhaps). The XML processor will pass this information along to an application, but it does not attempt to process the content of /standard/logo.gif. Parameter Entities Parameter entities can only occur in the document type declaration. A parameter entity declaration is identified by placing % (percent-space) in front of its name in the declaration. The percent sign is also used in references to parameter entities, instead of the ampersand. Parameter entity references are immediately expanded in the document type declaration and their replacement text is part of the declaration, whereas normal entity references are not expanded. Parameter entities are not recognized in the body of a document. Looking back at the element declarations in Example 2, you'll notice that two of them have the same content model: At the moment, these two elements are the same only because they happen to have the same literal definition. In order to make more explicit the fact that these two elements are semantically the same, use a parameter entity to define their content model. The advantage of using a parameter entity is two-fold. First, it allows you to give a descriptive name to the content, and second it allows you to change the content model in only a single place, if you wish to update the element declarations, assuring that they always stay the same:



Notation Declarations

Notation declarations [Section 4.7] identify specific types of external binary data. This information is passed to the processing application, which may make whatever use of it it wishes. A typical notation declaration is:



Do I need a Document Type Declaration? As we've seen, XML content can be processed without a document type declaration. However, there are some instances where the declaration is required: Authoring Environments Most authoring environments need to read and process document type declarations in order to understand and enforce the content models of the document. Default Attribute Values If an XML document relies on default attribute values, at least part of the declaration must be processed in order to obtain the correct default values. White Space Handling The semantics associated with white space in element content differs from the semantics associated with white space in mixed content. Without a DTD, there is no way for the processor to distinguish between these cases, and all elements are effectively mixed content. For more detail, see the section called White Space Handling, later in this document. In applications where a person composes or edits the data (as opposed to data that may be generated directly from a database, for example), a DTD is probably going to be required if any structure is to be guaranteed.

Including a Document Type Declaration If present, the document type declaration must be the first thing in the document after optional processing instructions and comments [Section 2.8]. The document type declaration identifies the root element of the document and may contain additional declarations. All XML documents must have a single root element that contains all of the content of the document. Additional declarations may come from an external DTD, called the external subset, or be included directly in the document, the internal subset, or both: This example references an external DTD, dbook.dtd, and includes element and attribute declarations for the ulink element in the internal subset. In this case, ulink is being given the semantics of a simple link from the XLink specification. Note that declarations in the internal subset override declarations in the external subset. The XML processor reads the internal subset before the external subset and the first declaration takes precedence. In order to determine if a document is valid, the XML processor must read the entire document type declaration (both internal and external subsets). But for some applications, validity may not be required, and it may be sufficient for the processor to read only the internal subset. In the example above, if validity is unimportant and the only reason to read the doctype declaration is to identify the semantics of ulink, reading the external subset is not necessary. You can communicate this information in the standalone document declaration [Section 2.9]. The standalone document declaration, standalone="yes" or standalone="no" occurs in the XML declaration. A value of yes indicates that only internal declarations need to be processed. A value of no indicates that both the internal and external declarations must be processed.

Other Markup Issues In addition to markup, there are a few other issues to consider: white space handling, attribute value normalization, and the language in which the document is written.

White Space Handling

White space handling [Section 2.10] is a subtle issue. Consider the following content fragment: Is the white space (the new line between and ) significant? Probably not. But how can you tell? You can only determine if white space is significant if you know the content model of the elements in question. In a nutshell, white space is significant in mixed content and is insignificant in element content. The rule for XML processors is that they must pass all characters that are not markup through to the application. If the processor is a validating processor [Section 5.1], it must also inform the application about which whitespace characters are significant. The special attribute xml:space may be used to indicate explicitly that white space is significant. On any element which includes the attribute specification xml:space='preserve', all white space within that element (and within subelements that do not explicitly reset xml:space ) is significant. The only legal values for xml:space are preserve and default. The value default indicates that the default processing is desired. In a DTD, the xml:space attribute must be declared as an enumerated type with only those two values. One last note about white space: in parsed text, XML processors are required to normalize all end-of-line markers to a single line feed character (&#A;) [Section 2.11]. This is rarely of interest to document authors, but it does eliminate a number of cross-platform portability issues.

Attribute Value Normalization The XML processer performs attribute value normalization [Section 3.3.3] on attribute values: character references are replaced by the referenced character, entity references are resolved (recursively), and whitespace is normalized.

Language Identification Many document processing applications can benefit from information about the natural language in which a document is written, XML defines the attribute xml:lang [Section 2.12] to identify the language. Since the purpose of this attribute is to standardize information across applications, the XML specification also describes how languages are to be identified.

Validity Given the preceding discussion of type declarations, it follows that some documents are valid and some are not. There are two categories of XML documents: well-formed and valid.

Well-formed Documents A document can only be well-formed [Section 2.1] if it obeys the syntax of XML. A document that includes sequences of markup characters that cannot be parsed or are invalid cannot be well-formed. In addition, the document must meet all of the following conditions (understanding some of these conditions may require experience with SGML):

• • • • • • • • •

The document instance must conform to the grammar of XML documents. In particular, some markup constructs (parameter entity references, for example) are only allowed in specific places. The document is not well-formed if they occur elsewhere, even if the document is well-formed in all other ways. The replacement text for all parameter entities referenced inside a markup declaration consists of zero or more complete markup declarations. (No parameter entity used in the document may consist of only part of a markup declaration.) No attribute may appear more than once on the same start-tag. String attribute values cannot contain references to external entities. Non-empty tags must be properly nested. Parameter entities must be declared before they are used. All entities except the following: amp, lt, gt, apos, and quot must be declared. A binary entity cannot be referenced in the flow of content, it can only be used in an attribute declared as ENTITY or ENTITIES. Neither text nor parameter entities are allowed to be recursive, directly or indirectly.

By definition, if a document is not well-formed, it is not XML. This means that there is no such thing as an XML document which is not well-formed, and XML processors are not required to do anything with such documents.

Valid Documents A well-formed document is valid only if it contains a proper document type declaration and if the document obeys the constraints of that declaration (element sequence and nesting is valid, required attributes are provided, attribute values are of the correct type, etc.). The XML specification identifies all of the criteria in detail.

Pulling the Pieces Together The XPointer and XLink specifications, currently under development, introduce a standard linking model for XML. In consideration of space, and the fact that the XLink draft is still developing, what follows is survey of the features of XLink, rather than a detailed description of the specification. In the parlance of XLink, a link expresses a relationship between resources. A resource is any location (an element, or its content, or some part of its content, for example) that is addressed in a link. The exact nature of the relationship between resources depends on both the application that processes the link and semantic information supplied. Some highlights of XLink are:

• • •

XLink gives you control over the semantics of the link. XLink introduces Extended Links. Extended Links can involve more than two resources. XPointer introduces Extended Pointers (XPointers). XPointers provide a sophisticated method of locating resources. In particular, XPointers allow you to locate arbitrary resources in a document, without requiring that the resource be identified with an ID attribute.

Since XML does not have a fixed set of elements, the name of the linking element cannot be used to locate links. Instead, XML processors identify links by recognizing the xml:link attribute. Other attributes can be used to provide additional information to the XML processor. An attribute renaming facility exists to work around name collisions in existing applications. Two of the attributes, show and actuate allow you to exert some control over the linking behavior. The show attribute determines whether the document linked-to is embeded in the current document, replaces the current document, or is displayed in a new window when the link is traversed. actuate determines how the link is traversed, either automatically or when selected by the user. Some applications will require much finer control over linking behaviors. For those applications, standard places are provided where the additional semantics may be expressed.

Simple Links A Simple Link strongly resembles an HTML
link:

Link Text

A Simple Link identifies a link between two resources, one of which is the content of the linking element itself. This is an in-line link. The locator identifies the other resource. The locator may be a URL, a query, or an Extended Pointer.

Extended Links Extended Links allow you to express relationships between more than two resources: This example shows how the relationships between a literary work, annotations, and literary criticism of that work might be expressed. Note that this link is separate from all of the resources involved. Extended Links can be in-line, so that the content of the linking element (other than the locator elements), participates in the link as a resource, but that is not necessarily the case. The example above is an out-of-line link because it does not use its content as a resource.

Extended Pointers Cross references with the XML ID/IDREF mechanism (which is similar to the #fragment mechanism in HTML) require that the document being linked-to has defined anchors where links are desired (and technically requires that both the ID and the IDREF occur in the same document). This may not always be the case and sometimes it is not possible to modify the document to which you wish to link. XML XPointers borrow concepts from HyTime and the Text Encoding Initiative (TEI). XPointers offer a syntax that allows you to locate a resource by traversing the element tree of the document containing the resource. For example,

child(2,oldjoke).(3,.) locates the third child (whatever it may be) of the second oldjoke in the document. XPointers can span regions of the tree. The XPointer

span(child(2,oldjoke),child(3,oldjoke))

selects the second and third oldjoke s in the document. In addition to selecting by elements, XPointers allow for selection by ID, attribute value, and string matching. In this article, the XPointer

span(root()child(3,sect1)string(1,"Here",0),

selects the first occurance of the word "Here" in the What Do XML Documents Look Like? section of this article. The link can be established by an extended link without modifying the target document. Note that an XPointer range can span a structurally invalid section of the document. The XLink specification does not specify how applications should deal with such ranges.

Extended Link Groups Out-of-line links introduce the possibility that an XML processor may need to process several files in order to correctly display the hypertext document. Following the annotated text example above, assuming that the actual text is read only, the XML processor must load at least the text and the document that contains the extended link. XLink defines Extended Link Groups for this purpose. Loading an Extended Link Group communicates which documents must be loaded to the XML processor. Extended Link Groups can be used recursively, and a steps attribute is provided to limit the depth of recursion.

Understanding The Pieces Some documents, particularly compound documents pulled together with XLinks, are likely to be composed of elements from multiple tag sets. For example, a technical article might be written using one DTD, but include mathematical equations written in MathML and vector graphics written in a third DTD. In order for a processing application to associate the correct semantics with an element, it must know which tag set the element comes from. XML solves this problem with namespaces. Namespaces in XML describes this system in detail. The principle is to allow a colon-delimited prefix to be associated with some external semantic via a URI. Then use of that prefix identifies the element as having the semantics described by the URI. For example: The para element in this example is explicitly identified as being in the namespace identified by the bk prefix, which must have been defined earlier in the document, and the cn and sep elements come from the ml namespace (presumably associated in some way with MathML).

Style and Substance HTML browsers are largely hard-coded. Although some browsers can base their formatting on Cascading Style Sheets (CSS), they still contain hard-coded conventions for documents which do not provide a stylesheet. A first level heading appears the way that it does largely because the browser recognizes the

tag. Again, since XML documents have no fixed tag set, this approach will not work. The presentation of an XML document is dependent on a stylesheet. The standard stylesheet language for XML documents is the Extensible Style Language (XSL). At the time of this writing, the XSL effort is well underway, but many questions remain unanswered. The XSL Working Group produced its first Working Draft on 18 Aug 1998.

Other stylesheet languages, like Cascading Style Sheets, are likely to be supported as well.

Conclusion In this article, most of the major features of the XML Language have been discussed, and some of the concepts behind XLink, Namespaces, and XSL have been described. Although some things have been left out in the interest of the big picture (such as character encoding issues), hopefully you now have enough background to pick up and read the XML Specifications without difficulty.

CSS Tutorial



Introduction



CSS Syntax



CSS Selectors



Where to Place It



CSS Text



CSS Colors



CSS Font



CSS Border



CSS Margin



CSS Links



CSS Layers



CSS List



CSS Cursors

CSS stands for Cascading Style Sheets. It is a way to divide the content from the layout on web pages.

How it works: A

style is a definition of fonts, colors, etc.

Each style has a unique name: a The

selector.

selectors and their styles are defined in one place.

In your HTML contents you simply refer to the

selectors whenever you want to activate a certain style.

For example: Instead of defining fonts and colors each time you start a new table cell, you can define a style and then, simply refer to that style in your table cells.

Compare the following examples of a simple table: Classic HTML
this is line 1
this is line 2
this is line 3


With CSS (assuming that a selector called subtext is defined)

this is line 1
this is line 2
this is line 3


While CSS lets you separate the layout from the content, it also lets you define the layout much more powerfully than you could with classic HTML.

With CSS, you will be able to: ­ define the look of your pages in one place rather than repeating yourself over and over again throughout

your site. (Ever get tired of defining colors and fonts each time you start a new cell in a table? Those days are over with CSS!)

­ easily change the look of your pages even after they're created. Since the styles are defined in one place you can change the look of the entire site at once. (Ever get tired of replacing tags throughout your site when you want to change the look of a certain element? Those days are over with CSS!)

­ define font sizes and similar attributes with the same accuracy as you have with a word processor - not being limited to just the seven different font sizes defined in HTML.

­ position the content of your pages with pixel precision. ­ redefine entire HTML tags. Say for example, if you wanted the bold tag to be red using a special font - this can be done easily with CSS.

­ define customized styles for links - such as getting rid of the underline. ­ define layers that can be positioned on top of each other (often used for menus that pop up). Your pages will load faster, since they aren't filled with tags that define the look. The style definitions are kept in a single CSS document that is only loaded once when a visitor enters your site.

The one disadvantage is:

­ these will only work on version 4 browsers or newer. However, more than 95% of all browsers live up to that.

Syntax: The CSS syntax is made up of three parts: a selector, a property and a value:

selector {property: value} The selector is normally the HTML element/tag you wish to define, the property is the attribute you wish to change, and each property can take a value. The property and value are separated by a colon and surrounded by curly braces:

body {color: black} If the value is multiple words, put quotes around the value:

p {font-family: "sans serif"} Note: If you wish to specify more than one property, you must separate each property with a semi-colon. The example below shows how to define a center aligned paragraph, with a red text color:

p {text-align:center;color:red} To make the style definitions more readable, you can describe one property on each line, like this:

p

{ text-align: center; color: black; font-family: arial }

Grouping: You can group selectors. Separate each selector with a comma. In the example below we have grouped all the header elements. All header elements will be green:

h1,h2,h3,h4,h5,h6

{ color: green }

Class Selector: With the class selector you can define different styles for the same type of HTML element. Say that you would like to have two types of paragraphs in your document: one right-aligned paragraph, and one center-aligned paragraph. Here is how you can do it with styles:

p.right {text-align: right} p.center {text-align: center} You have to use the class attribute in your HTML document:



This paragraph will be right-aligned.

This paragraph will be center-aligned.

Note: Only one class attribute can be specified per HTML element! The example below is wrong:



This is a paragraph.

You can also omit the tag name in the selector to define a style that will be used by all HTML elements that have a certain class. In the example below, all HTML elements with class="center" will be center-aligned:

.center {text-align: center} In the code below both the h1 element and the p element have class="center". This means that both elements will follow the rules in the ".center" selector:

This heading will be center-aligned

This paragraph will also be center-aligned.

Do NOT start a class name with a number! It will not work in Mozilla/Firefox.

id Selector: With the id selector you can define the same style for different HTML elements. The style rule below will match any element that has an id attribute with a value of "green":

#green {color: green} The rule above will match both the h1 and the p element:

Some text

Some text

The style rule below will match a p element that has an id with a value of "para1":

p#para1 { text-align: center; color: red } The style rule below will match any p element that has an id attribute with a value of "green":

p#green {color: green} The rule above will not match an h1 element:

Some text

Do NOT start an ID name with a number! It will not work in Mozilla/Firefox.

CSS Comments: You can insert comments into CSS to explain your code, which can help you when you edit the source code at a later date. A comment will be ignored by the browser. A CSS comment begins with "/*", and ends with "*/", like this:

/* This is a comment */ p { text-align: center; /* This is another comment */ color: black; font-family: arial }

Selectors are the names that you give to your different styles. In the style definition you define how each selector should work (font, color etc.). Then, in the body of your pages, you refer to these selectors to activate the styles. For example: <style type="text/css"> B.headline {color:red; font-size:22px; fontfamily:arial; text-decoration:underline} This is normal bold
This is headline style bold

In this case B.headline is the selector. The above example would result in this output: This is normal bold

This is headline style bold There are three types of selectors:

HTML selectors Used to define styles associated to HTML tags. (A way to redefine the look of tags)

Class selectors Used to define styles that can be used without redefining plain HTML tags.

ID selectors Used to define styles relating to objects with a unique ID (most often layers)

The general syntax for an HTML selector is: HTML selectors {Property:Value;}

For example: <style type="text/css"> B {font-family:arial; font-size:14px; color:red} This is a customized headline style bold

HTML selectors are used when you want to redefine the general look for an entire HTML tag. The general syntax for a Class selector is: .ClassSelector {Property:Value;}

For example:

<style type="text/css"> .headline {font-family:arial; font-size:14px; color:red} This is a bold tag carrying  the headline class
This is an italics tag  carrying the headline class

Class selectors are used when you want to define a style that does not redefine an HTML tag entirely. When referring to a Class selector you simply add the class to an HTML tag like in the above example (class="headline").

SPAN and DIV as carriers

Two tags are particularly useful in combination with class selectors: <SPAN> and
. Both are "dummy" tags that don't do anything in themselves. Therefore, they are excellent for carrying CSS styles. <SPAN> is an "inline-tag" in HTML, meaning that no line breaks are inserted before or after the use of it.

is a "block tag", meaning that line breaks are automatically inserted to distance the block from the surrounding content (like

or

tags).

has a particular importance for layers. Since layers are separate blocks of information.
is an obvious choice when defining layers on your pages.

The general syntax for an ID selector is: #IDSelector {Property:Value;}

For example:

<style type="text/css"> #layer1 {position:absolute; left:100;top:100; zIndex:0} #layer2 {position:absolute; left:140;top:140; z­ Index:1}
THIS  IS LAYER 1
POSITIONED AT  100,100
THIS  IS LAYER 2
POSITIONED AT  140,140


ID selectors are used when you want to define a style relating to an object with a unique ID. This selector is most widely used with layers (as in the above example), since layers are always defined with a unique ID.

Grouped Selector

Most often selectors will share some of the same styles, for example, being based on the same font. In these cases, rather than defining the font for each and every selector, one by one, you can group them, and thus assign the font to all the selectors at once.

Look at this example, made without grouping: .headlines{ font­family:arial; color:black; background:yellow;  font­size:14pt; } .sublines { font­family:arial; color:black; background:yellow;  font­size:12pt; } .infotext { font­family:arial; color:black; background:yellow;  font­size:10pt; }

As you can see, the only style that varies is the font-size. In the next example we have grouped the selectors, and defined the common styles at once.

.headlines, .sublines, .infotext { font-family:arial; color:black; background:yellow; } .headlines {font­size:14pt;} .sublines {font­size:12pt;} .infotext {font­size: 10pt;}

Less to type, easier to change and guaranteed to be the same for all styles. CSS can be added to your pages at 3 different levels. It is possible to create CSS styles that only work for the single tag it is defined for. Single tag CSS is used when the style is used in a single place on the entire site. Usually a certain style appears more than once on your pages, and thus you should use the second technique: adding styles that are defined once for the entire page.

If, however, that certain style is used on more than a single page, you should use the third - and most powerful technique described: adding styles that are defined once for the entire site.

The following Sections will explain each of these techniques.... Single Tags / Inline Style Sheet

CSS can be defined for single tags by simply adding style="styledefinition:styleattribute;" to the tags. Look at this example: It is NOT me.

You should limit your use of single tag CSS. If you define your styles for each and every tag they're used on, you will lose much of the power associated with CSS.

For example, you will have to define the style over and over again whenever it's used, rather than just defining it once and then referring to that one definition whenever it's used.

Furthermore, if you wanted to change a certain style, you'd have to change it all over in your document, rather than in one place.

Single Pages / Internal Style Sheet

CSS can be defined for entire pages by simply adding a style definition to the head section.

Look at this example: MY CSS PAGE <style type="text/css"> .headlines, .sublines, infotext {font-face:arial; color:black; background:yellow; font-weight:bold;} .headlines {font­size:14pt;} .sublines {font­size:12pt;} .infotext {font­size: 10pt;} <span class="headlines">Welcome
This is an example page using CSS.
The example is really simple,
and doesn't even look good,
but it shows the technique.
As you can see:
The styles even work on tables.
Example from Academic Articles.




In the above example, although we used the sublines style twice, we only had to define it once: in the section.

By defining styles for entire pages, you will gain the freedom to easily change the styles even after the entire page has been made.

This is an obvious advantage for you as a designer. But the advantage is on the visitors side as well. Since the styles are only defined in one place, the page size will be smaller, and thus faster to load. There is a way to emphasize these advantages even more: using external CSS styles that work for entire sites. Entire Sites / External Style Sheet

CSS can be defined for entire sites by simply writing the CSS definitions in a plain text file that is referred to from each of the pages in the site.

Rather than writing the entire CSS definition on each page, as in the previous examples, you can write it to a text file that is only loaded on the first page that a visitor sees at your site. When the visitor jumps to other pages, the CSS text file will be cached and thus doesn't have to be transferred via the internet for subsequent pages.

This means that your pages will load faster while at the same time you will have extreme flexibility to change the style for your entire site even after it has been made.

Look at this example: File: example.html MY CSS PAGE <span class="headlines">Welcome
This is an example of a page using CSS.
The example is really simple,
and doesn't even look good,
but it shows the technique.
As you can see:
The styles even work on tables.
Example from Academic  Articles.



The above example is the exact same as we used for CSS defined for entire pages, with one important exception: There is no style definition on the page. Instead we added a reference to an external style sheet:

This means that the browser will look for a file called whatever.css and insert it at the place where the reference was found in the html document.

So in order to complete our example we need to have a file called whatever.css that looks like this: File: whatever.css

.headlines, .sublines, infotext {font-face:arial; color:black; background:yellow; font-weight:bold;} .headlines {font-size:14pt;} .sublines {font-size:12pt;} .infotext {font-size: 10pt;}

Now if you just add the line to the of all your pages, then the one style definition will be in effect for your entire site.

Imagine the power and flexibility this gives you to make changes to the layout even after the site is done. But also realize how using an external style sheet will guarantee that all pages are following the same thread. There won't be single pages that you forgot to update when you decided to change the style for your headers.

At this point of the tutorial you should know: 1: how to define styles for tags, classes and objects with ID's. 2: how to group styles and make them context dependent 3: how to add styles to single tags, single pages and entire sites

All we need now is a walkthrough of the various style attributes that can be assigned. We will divide them into three categories: 1: Inline attributes. (Works on tags like: <SPAN>, and ). 2: Block attributes. (Works on block tags:
, and

). 3: Link attributes. (Works on links and use a special syntax).

CSS has several options for defining the styles of text. These options can entirely replace the tag, but there's even more. CSS allows you to define these styles much more powerfully than you could ever do with plain HTML.

FONT PROPERTIES

Property fontfamily

Values

font-family:arial

font name 4+ 4+ font-family:arial, generic font 4+ 4+ helvetica

font-style normal

italic oblique fontvariant fontweight

font-size

NS IE Example

4+ 4+ font-style:normal 4+ 4+ font-style:italic 4+ font-style:oblique 4+ font-variant:normal 4+ font-variant:small-caps

normal small-caps normal bold bolder lighter 100-900

4+ 4+ 4W 4W 4+

4+ 4+ 4+ 4+ 4+

font-weight:normal font-weight:bold font-weight:bolder font-weight:lighter font-weight:250

normal length length absolute absolute absolute absolute absolute absolute absolute relative relative percentage

4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+

4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+

font-size:normal font-size:14px font-size:14pt font-size:xx-small font-size:x-small font-size:small font-size:medium font-size:large font-size:x-large font-size:xx-large font-size:smaller font-size:larger font-size:75%

4P:problems, 4M:Mac only, 4W:Windows only

ASSIGNING ALL FONT ATTRIBUTES AT ONCE An example of a typical font definition would be: B {font-family:arial, helvetica; font­size:12px;  font­weight:bold;}

But since all font attributes can actually be expressed with the font property we could actually write it this way: B {font:arial, helvetica 12px bold}

The above is obviously a shorter way to specify font settings - but in reality it is less useful than one might think. The reason is that you'd be assigning the same font face to all your styles, for example, while you'd want different font weights and sizes for headers and content areas etc.

TEXT PROPERTIES Despite the font properties listed above there are some options for defining text properties such as alignments, underlines, etc.

Property

Values

NS IE Example

line-height

normal number length percentage

4W 4+ 4+ 4+

4+ 4P 4+ 4P

line-height:normal line-height:1.5 line-height:22px line-height:150%

text-decoration none

4+ 4M text-decoration:none underline 4+ 4+ text-decoration:underline 4W text-decoration:overline overline line-through 4+ 4+ text-decoration:line-through text-decoration:blink blink 4+

text-transform

none capitalize uppercase lowercase

4+ 4+ 4+ 4+

4W 4W 4W 4W

text-transform:none text-transform:capitalize text-transform:uppercase text-transform:lowercase

text-align

left right center justify

4+ 4+ 4+ 4+

4+ 4+ 4+ 4W

text-align:left text-align:right text-align:center text-align:justify

text-indent

length 4+ 4+ text-indent:20px; percentage 4+ 4+ text-indent:10%

white-space

normal pre

4+ 4+

white-space:normal white-space:pre

4P:problems, 4M:Mac only, 4W:Windows only

Note:

line­height : When using a number (such as 1.5) the number refers to the font size, where 1.5 would mean that a 1.5 lines spacing (using the current font size) will be inserted between the lines.

text­transform : Capitalize sets the first letter of each word in uppercase. Uppercase forces all letters to uppercase. Lowercase forces all letters to lowercase.

text­indent : Use this to indent the first word of a paragraph.

white­space : If white-space is set to pre the browser will show all spaces in the text, rather than ignoring all occurrences of more than one space. This is similar to the <pre> tag in plain HTML. Since the white-space is only supported by NS you should use the <pre>  tag instead.

The official CSS standard provided by W3C also includes properties for word spacing, letter spacing and vertical align, but these aren't supported by today's browsers.

COLORS As you can see, the above CSS properties can replace all text formatting that can be done with plain HTML with one exception: the color.

The color is not part of the font collection in CSS - rather it has its own definition. If you want to add a color to the text in the above example you'd do it this way: B {font:arial, helvetica 12px bold; color:red}

CSS has several options for defining colors of both text and background areas on your pages. These options can entirely replace the color attributes in plain HTML. In addition, you get new options that you just didn't have in plain HTML.

For example, in plain HTML, when you wanted to create an area with a specific color you were forced to include a table. With CSS, you can define an area to have a specific color without that area being part of a table.

Or even more useful, in plain HTML when working with tables, you had to specify font attributes and colors etc. for each and every table cell. With CSS you can simply refer to a certain class in your

tags.

COLOR PROPERTIES Property color background­color background­image

background­repeat

background­attachment

background­position

background

Values transparent none url() repeat repeat-x repeat-y no-repeat scroll fixed top center bottom left right

NS 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+

IE 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+

4P:problems, 4M:Mac only, 4W:Windows only

Setting colors Basically you have three color options with CSS: 1: Setting the foreground color for contents 2: Setting the background color for an area 3: Setting a background image to fill out an area

In the next section we will list the different properties that let you do that.

In plain HTML, colors can either be entered by name (red, blue etc.) or by a hexadecimal color code (for example: #FF9900).

With CSS you have these options:

Common name You can define colors with the use of common names, by simply enter the name of the desired color. For example: .myclass {color:red; background-color:blue;}

Hexadecimal value You can define colors with the use of hexadecimal values, similar to how it's done in plain HTML. For example: .myclass {color:#000000; background-color:#FFCC00;}

RGB value You can define colors with the use of RGB values, by simply entering the values for amounts of Red, Green and Blue. For example: .myclass {color:rgb(255,255,204); backgroundcolor:rgb(51,51,102);}

You can also define RGB colors using percentage values for the amounts of Red, Green and Blue: For example: .myclass {color:rgb(100%,100%,81%); backgroundcolor:rgb(81%,18%,100%);}

Setting background colors Background colors are defined similar to the colors mentioned above. For example you can set the background color of the entire page using the

BODY selector:

BODY {background-color:#FF6666;}

Setting a background image CSS lets you set a background image for both the page and single elements on the page.

In addition, CSS offers several positioning methods for background images.

You can define the background image for the page like this: BODY {background-image:url(myimage.gif);}

You can control the repetition of the image with the background­repeat property. background­repeat:repeat Tiles the image until the entire page is filled, just like an ordinary background image in plain HTML.

background­repeat:repeat­x Repeats the image horizontally - but not vertically.

background­repeat:repeat­y Repeats the image vertically - but not horizontally.

background­repeat:no­repeat Does not tile the image at all.

Positioning a background Background positioning is done by entering a value for the left position and top position separated by a space.

In this example the image is positioned 75 pixels from the upper left corner of the page: BODY {background-image:url(myimage.gif); background-position: 75px 75px;}

Note: Background positioning is not supported by Netscape 4 browsers.

Fixing a background You can fixate an image at a certain position so that it doesn't move when scrolling occurs. BODY {background-image:url(myimage.gif); background-attachment: fixed;}

Note: Background fixation is not supported by Netscape 4 browsers.

Setting multiple background values Rather than defining each

background property.

background property with its own property you can assign them all with the use of the

Look at this example: BODY {background:green url(myimage.gif) repeat-y fixed 75px 75px;}

The CSS font properties allow you to change the font family, boldness, size, and the style of a text. Note: In CSS1 fonts are identified by a font name. If a browser does not support the specified font, it will use a default font. Browser support: IE: Internet Explorer, F: Firefox, N: Netscape. W3C: The number in the "W3C" column indicates in which CSS recommendation the property is defined (CSS1 or CSS2). Property

Description

Values

IE

F

N

W3C

font

A shorthand property for setting all of the properties for a font in one declaration

font-style font-variant font-weight font-size/line-height font-family caption icon menu message-box small-caption status-bar

4

1

4

1

font-family

A prioritized list of font family names and/or generic family names for an element

family-name generic-family

3

1

4

1

font-size

Sets the size of a font

xx-small x-small small medium large x-large xx-large smaller larger length %

3

1

4

1

font-size-adjust

Specifies an aspect value for an element that will preserve the xheight of the first-choice font

none number

-

-

-

2

font-stretch

Condenses or expands the current normal font-family wider narrower ultra-condensed extra-condensed condensed semi-condensed semi-expanded expanded extra-expanded ultra-expanded

-

-

-

2

font-style

Sets the style of the font

normal italic oblique

4

1

4

1

font-variant

Displays text in a small-caps font or a normal font

normal small-caps

4

1

6

1

font-weight

Sets the weight of a font

normal bold bolder lighter 100 200 300 400 500 600 700 800 900

4

1

4

1

ASP Tutorial

• • • • • • • • • • •

What are Active Server Pages? Displaying Date, Time and Text Using Variables and Forms If...Then and For...Next instructions Do...Loop and Select...Case instructions Subroutines and Include/virtual Session and Application methods Dictionary Object Cookies Open Read and Create files Introduction to Global.asa

• • • •

Using ASP and javascript together Using Arrays Displaying pictures from an ASP file Active Server Pages Server-Side Scripting Programmer's Reference

What Are Active Server Pages? Active Server Pages (ASPs) are Web pages that contain server-side scripts in addition to the usual mixture of text and HTML (Hypertext Markup Language) tags. Server-side scripts are special commands you put in Web pages that are processed before the pages are sent from your Personal Web Server to the Web browser of someone who's visiting your Web site. . When you type a URL in the Address box or click a link on a Web page, you're asking a Web server on a computer somewhere to send a file to the Web browser (sometimes called a "client") on your computer. If that file is a normal HTML file, it looks exactly the same when your Web browser receives it as it did before the Web server sent it. After receiving the file, your Web browser displays its contents as a combination of text, images, and sounds. In the case of an Active Server Page, the process is similar, except there's an extra processing step that takes place just before the Web server sends the file. Before the Web server sends the Active Server Page to the Web browser, it runs all server-side scripts contained in the page. Some of these scripts display the current date, time, and other information. Others process information the user has just typed into a form, such as a page in the Web site's guestbook. To distinguish them from normal HTML pages, Active Server Pages are given the ".asp" extension. What Can You Do with Active Server Pages? There are many things you can do with Active Server Pages.

• •

You can display date, time, and other information in different ways. You can make a survey form and ask people who visit your site to fill it out, send emails, save the information to a file, etc

What Do Active Server Pages Look Like? The appearance of an Active Server Page depends on who or what is viewing it. To the Web browser that receives it, an Active Server Page looks just like a normal HTML page. If a visitor to your Web site views the source code of an Active Server Page, that's what they see: a normal HTML page. However, the file located in

the server looks very different. In addition to text and HTML tags, you also see server-side scripts. This is what the Active Server Page looks like to the Web server before it is processed and sent in response to a request. What Do Server-Side Scripts Look Like? Server-side scripts look a lot like HTML tags. However, instead of starting and ending with lesser-than ( < ) and greater-than ( > ) brackets, they typically start with <% and end with %>. The <% is called an opening tag, and the %> is called a closing tag. In between these tags are the server-side scripts. You can insert server-side scripts anywhere in your Web page--even inside HTML tags. Do You Have to Be a Programmer to Understand Server-Side Scripting? There's a lot you can do with server-side scripts without learning how to program. For this reason, much of the online Help for Active Server Pages is written for people who are familiar with HTML but aren't computer programmers. Displaying Date, Time and Text Displaying the Current Date and Time The date and time described in this section are those that are on the server. Date To display the current date by itself in a Web page, type: <% =date %> at the point where you want it to appear. When you view the page in your browser, you should see something like this: Thu, Jan 23, 1997 Note: Even though "=date" is a short script, it's actually made up of two parts. The "date" part tells the server, "Get me the date." The equal sign (=) tells the server to display the date in the Web page. If you typed just: <% date %> the server would get the current date from your system, but that's all. It wouldn't display it. There are times when it makes sense to use an ASP function without the equal sign. Time To display the current time by itself, type: <% =time %> where you want it to appear. When you view the page, you should see something like this: 4:19:46 PM Now (Date and Time) To display the current date and time, type: <% =now %> where you want them to appear. When you view the page, you should see something like this: 1/23/97 4:19:46 PM Changing the Way Date and Time are Displayed You can also use Active Server Pages (ASP) functions to customize the way the current date and time are displayed on your Web page. To do this, use the now function together with the following formatting functions. Month and Monthname To display the number of the current month in a Web page, type: <% =month(now) %> where you want it to appear. When you view the page in your browser, you'll see a 1 if the current month is January, 2 if it's February, and so on. To display the name of the current month, type: <% =monthname(month(now)) %> where you want it to appear.

Day To display the day of the current month, type: <% =day(now) %> where you want it to appear. When you view the page, you'll see a number between 1 and 31. Year To display the current year, type: <% =year(now) %> where you want it to appear. Example Suppose you wanted to display today's date as day/month/year instead of month/day/year. To do so, you would use the day, month, and year ASP functions together, by typing: <% =day(now) %>/<% =month(now) %>/<% =year(now) %> When you viewed the page, you would see something like this: 23/1/1997 Later we'll see how you can change this so only the last two digits of the year are displayed, like this: 23/1/97 Weekday and Weekdayname To display the day of the week as a number from 1 to 7 in a Web page, type: <% =weekday(now) %> where you want it to appear. When you view the page in Internet Explorer, you'll see a 1 if today is Sunday, 2 if it's Monday, and so on. To display the day of the week by name, type: <% =weekdayname(weekday(now)) %> where you want it to appear. Hour, Minute, and Second To display just the hour part of the current time, type: <% =hour(now) %> where you want it to appear. The hour function is based on a 24-hour clock. When you view the page, you'll see a number between 0 and 23. To display just the minutes part of the current time, type: <% =minute(now) %> where you want it to appear. When you view the page, you'll see a number between 0 and 59. To display just the seconds part of the current time, type: <% =second(now) %> where you want it to appear. When you view the page, you'll see a number between 0 and 59. Example Try typing this into a Web page: The time is <% =time %>. That means it's <% =minute(now) %> minutes past <% =hour(now) %> o'clock. When you view the page in Internet Explorer, you should see something like this: The time is 1:36:05 PM. That means it's 36 minutes past 13 o'clock. Remember, the hour function is based on a 24-hour clock. Later we'll see how to convert from the 24-hour clock to a 12-hour clock. Timevalue You probably won't ever use the timevalue function. It takes the different ways you can write the time, such as "2:24PM" and "14:24," and returns them in this format: "2:24:00 PM." This can be useful if you're using a function that needs to be given the time in that exact format. Example Earlier in this section we saw how you can use the hour, minute, and second functions to break up the time into hours, minutes, and seconds. With the timevalue function, you can put them back together. Type this into a Web page: When it's 23 minutes and 5 seconds past 4 o'clock in the afternoon, that means it's <% =timevalue("16:23:05") %>. This is the same as <% =timevalue("4:23:05PM") %> or <%

=timevalue("16:23:05PM") %>. Make sure you type "16:23:05PM" and not "16:23:05 PM." The "05" and the "PM." should be run together, not separated by a space. When you view the page in Internet Explorer, you should see: When it's 23 minutes and 5 seconds past 4 o'clock in the afternoon, that means it's 4:23:05 PM. This is the same as 4:23:05 PM or 4:23:05 PM. Displaying Text len The len function tells you how many characters are in a word or sequence of words. (The name "len" is an abbreviation of "length.") All characters are counted, including the space character. For example, to find the length of the sentence "The cat is on the mat," type this into a Web page: There are <% =len("The cat is on the mat.") %> characters in "The cat is on the mat." When you view the page in Internet Explorer, you should see this: There are 22 characters in "The cat is on the mat." left You can use the left function to look at the first few characters of a word or sequence of words. For example, to find the first character of "Frankenstein," type this into a Web page: "Frankenstein" begins with the letter <% =left("Frankenstein", 1) %>. When you view the page, you should see this: "Frankenstein" begins with the letter F. right To look at the last few characters of a word or sequence of words, use the right function. For example, to find the last three letters of "Wednesday," type this into a Web page: The last three letters of "Wednesday" are: <% =right("Wednesday", 3) %>. When you view this page, you should see this: The last three letters of "Wednesday" are: day. Example What if you wanted to take a few letters from the middle of something? How would you specify exactly where in the middle you wanted to be? For example, how would you take out just the "apple" part of the word "pineapples"? You could start with the fifth character from the left and then stop at the second character from the right. Or you could do it the following way. Try typing this into a Web page: <% =right("pineapples", 6) %> <% =left(right("pineapples", 6), 5) %> This line takes the last six letters of the word "pineapples," which make up the word "apples." Then it takes the first five letters of the word "apples," which make up the word "apple." When you view this page in Internet Explorer, you should see this: apples apple Then try typing this into a Web page: <% =left("pineapples", 9) %> <% =right(left("pineapples", 9), 5) %> This line takes the first nine letters of the word "pineapples," which make up the word "pineapple." Then it takes the last five letters of the word "pineapple," which make up the word "apple." When you view this page, you should see this: pineapple apple

Cool Things You Can Do with Date, Time, and Text Here are some examples of interesting things you can do with date, time, and text functions. Link of the Day What if you wanted to have a link that pointed to a different page every day of the week? Here's how you can do that. First, choose the pages (HTML files) on your Web site that you want your link to point to. Name them "Sunday.htm," "Monday.htm," and so on. (If you don't have seven different HTML files, you can copy some of the files or make aliases on your Macintosh to them. The important thing is that there has to be one file or alias for every day of the week.) To make the link, type
.htm>Link of the Day where you want it to appear. When you click this link in Internet Explorer, it will take you to today's page. Another Way to Display Today's Date Earlier we saw how to change the date display from month/day/year to day/month/year like this: 23/1/1997 We can also change the date display so only the last two digits of the year are included. To do this, type <% =day(now) %>/<% =month(now) %>/<% =Right((year(now)), 2) %> Now when you view the page, you should see something like this: 23/1/97 Another Way to Display the Time In an earlier example, we wrote a server-side script to display the current time in words, such as: "The time is 36 minutes and 5 seconds past 13 o'clock." This script used the ASP hour function, which returns just the hour part of the current time, based on a 24-hour clock. In this example, we'll see how to change 24-hour clock times such as "13 o'clock" to 12-hour clock times ("1 o'clock PM"). To do this, we'll need to make the server-side script that uses the hour function a little more complicated. Instead of <% =hour(now) %> o'clock we'll need to write a script that looks at the hour and does one of the following:

• • • •

If the hour is 0 (zero), the script displays "midnight." If the hour is 12, the script displays "noon." If the hour is between 1 and 11, the script doesn't change it, but it displays "AM" after "o'clock." If the hour is between 13 and 23, the script subtracts 12 (to make it a number between 1 and 11) and displays "PM" after "o'clock."

The script is shown below. It isn't written quite the way a programmer would write it, but it works, and it's fairly easy to understand, since it follows the items in the bulleted list above exactly. The hour is <% if hour(now) = 0 then %> midnight. <% end if if hour(now) = 12 then %> noon. <% end if if (hour(now) >= 1) and (hour(now) <= 11) then %> <% =hour(now) %> o'clock AM. <% end if if (hour(now) >= 13) and (hour(now) <= 23) then %> <% =hour(now) - 12 %> o'clock PM. <% end if %> If you type (or better yet, cut-and-paste) this script in a Web page, when you view the page, you should see something like this: The hour is 4 o'clock PM.

Using Variables, and Forms in Active Server Pages Forms are a convenient way to communicate with visitors to your Web site. Using forms, you can create a survey form and ask visitors to fill it out. When they fill out the form, you can process the results automatically.

With forms, there are two steps: first you create the form, and then you process it. To create a form for an Active Server Page, just create a standard HTML form. To try out this example, create an HTML file ("form_response.html") and cut-and-paste the following text into it.

form_response.html

try !

Asking for information

Your name:
Your email:
Active Server Pages provide a mechanism for processing forms that, unlike CGI scripting, doesn't involve serious programming: the Request.Form. Considering

the

form

above,

we

may

form_response.asp

create

the

file

bellow

and

get

a

response.

try !

Responding to a form Your name is <% =Request.Form("name") %>
Your email is <% =Request.Form("email") %> To display the contents of each field in the form, type: <% =Request.Form(fieldname) %> where fieldname is the name of the field.

Creating a Variable You'll probably want to do more with your forms than display their contents in a Web page. For example, based on the contents of the form, you may want to create a variable and insert that variable in different places of your response page. You may need to create a variable. To do that, just make up a name and set it equal to the contents of the field.

For example, if you have a field called "CatName" in your form, you can save it into a variable called "TheName" by typing: <% TheName = Request.Form("CatName") %> If you want to display "VisitorName" several times within a text you only need to include the variable in the text. For example: My cat´s name is <% =TheName %>. Do you want to see <% =TheName %>?. Example The form in this example asks users to introduce their names and their favorite color: red, blue, or green. When the form is received, the server responds displaying these data. nameandcolor.html

try !

Name and Color
Let me know your Name and Favorite Color:

YOUR NAME:

COLOR: Red Green Blue

Now,

create

an

ASP

file

("nameandcolor.asp")

nameandcolor.asp

and

cut-and-paste

the

try !

Name and Color <% TheName = Request.Form("YOURNAME") %> <% colornumber = Request.Form("COLOR") %> Hi, <% =Thename %>.
I know your favorite color is <% if colornumber = "1" then %> red <% end if %> <% if colornumber = "2" then %> green <% end if %> <% if colornumber = "3" then %> blue <% end if %>.

following

text

into

it.

If....Then...Else The If....Then...Else instructions sequence is very similar to the one we may find in different kind of scripting languages. Let's check an example.

<% AA="water" If AA="water" Then response.write ("I want to drink Else response.write ("I want to drink milk") End %>

water")

If

We may use it this way: <% AA="water" If AA="water" Then %> I want to drink water <% Else %> I want to drink milk <% End If %> In both cases we have checked a condition (AA="water"), and we have get a positive instruction (to write the sentence "I want to drink water"). We are allowed to execute any kind of instructions (including If....then....Else) and as many instructions as we want .

For....Next This instructions is also similar in different programming languages. Let's see a typical example.

example.asp Try ! I want to say "Hello" 10 times
<% For mynumber = 1 to 10 %> <% =mynumber %> Hello
<% Next %> END In this case we have defined a variable ("mynumber") and using the For...Next instruction we have repeated 10 times line 4. Similarly to If....Then....Else instruction, we are allowed to execute any kind of instructions and as many of them as we want .

The

For...Next

instruction

allows

to

define

the

value

of

the

increment.

<% For mynumber = 1 to 20 STEP 2 response.write("Hello
") Next %> <% For mynumber = 20 to 1 STEP -2 response.write("Hello
") Next %> In both cases we will get the same response ("Hello" 10 times). The increment may be positive or negative as shown in the example. Subroutines Subroutines have the same utility in ASP as it has in other languages. In the next two examples, we have asked our visitors his name, and depending on that answer a different response is sent to the client. The response will be the same in both cases, but in the second one subroutines are used. The use of subroutines may be very useful when there are a lot of instructions to be perform within a subroutine. This way it will allow us to simplify the structure of our script. Example 1 <% TheName=request.form("name) if TheName="John" then response.write ("Hi, John. How are you?") response.write ("
Did you know I got married last month?") else response.write ("Hi. How are you?") end if %> Example 2 <% TheName=request.form("name) if TheName="John" ResponseToJohn() else ResponseToUnknown() end if

then

Sub ResponseToJohn() response.write ("Hi, John. How are you?") response.write ("
Did you know I got married last month?") End Sub Sub response.write End Sub %>

ResponseToUnknown() ("Hi. How are

you?")

In order to call a subroutine, we will use this kind of code: Whatever() Where Whatever is the name of the subroutine (it is recommended to use a very descriptive name of the task we want to perform within the subroutine to make it easier to understand the script). We may also provide information to the subroutine in order to perform the specified task. The data will be provided this way: Whatever(data1, data2 ... dataN) In the following example we will provide different data to a unique subroutine depending on the Name of the person provided throw a form: Example 3 <% TheName=request.form("name)

1 2 3 if TheName="John" then 4 ResponseToVisitor(35,Sue,New York) 5 else 6 if TheName="Peter" then 7 ResponseToVisitor(33,Sally,Los Angeles) 8 else 9 response.write("Who are you?") 10 end if 11 end if 12 13 Sub ResponseToVisitor(AA,BB,CC) 14 response.write ("I know your are" & AA & "years old, 15 ") 16 response.write ("you are married to" & BB & ", and") 17 response.write ("you are living in " & CC) 18 End Sub 19 %> In line 14 it is specified AA is the first variable to be get, BB the second one, and CC the third one. The values for the three variables are provided in the same order in line 5 or line 8. The example above also shows subroutines are very useful to avoid repeating a specific number of tasks several times within the script, so that the script looks more organized and it is smaller.

Include/virtual Server Site includes or SSI is a very simple programing language (see a small tutorial) but it also has a very limited number of instructions. We will consider only one option SSI allows us to use within our asp scripts: include/virtual. In the next example we will use the include option of SSI in a our asp script (response.asp). This command allows as to add a set of instructions from different files (file1.txt and file2.txt bellow) and execute them. Example 4 response.asp <% TheName=request.form("name)

if

TheName="John" then %> -->

File1.html Hi, John.
I know your are 31 years old, you are married to Sue, and you are living in New York. File2.asp <% for i=1 to 3 response.write(Thename & "...
") next response.write("Who are you?") %>

In this case, if the name of the person who is visiting our page is John, then we will respond with file1.html. If not, then we will execute some asp instructions from file2.asp. The include file must be a text file (.txt, .html, .htm, .shtml, .asp...). Although we have used file1.html and file2.asp, the script will work exactly in the same way with file1.txt and file2.txt (changing the name of the files would have no effect).

By

using

SSI

and

asp

we

may

also

get

secret_page.asp Try ! <% UserName=request.form ("username") Password=request.form("password") if UserName="myusername" and Password="mypassword" then %> <% else %>
Username:
Password:
<% end if %> secret_info.txt This is my secret information:
My name is John.
My surname is Smith.

End of secret information.

a

secret

page:

In this case it is convenient to save secret_info.txt file in the cgi-bin directory (the .txt file is not accessible by visitors from this directory, but it will be accessible from our top directory).

Subroutines Subroutines have the same utility in ASP as it has in other languages. In the next two examples, we have asked our visitors his name, and depending on that answer a different response is sent to the client. The response will be the same in both cases, but in the second one subroutines are used. The use of subroutines may be very useful when there are a lot of instructions to be perform within a subroutine. This way it will allow us to simplify the structure of our script. Example 1 <% TheName=request.form("name) if TheName="John" then response.write ("Hi, John. How are you?") response.write ("
Did you know I got married last month?") else response.write ("Hi. How are you?") end if %> Example 2 <% TheName=request.form("name) if TheName="John" ResponseToJohn() else ResponseToUnknown() end if

then

Sub ResponseToJohn() response.write ("Hi, John. How are you?") response.write ("
Did you know I got married last month?") End Sub Sub response.write End Sub

ResponseToUnknown() ("Hi. How are

you?")

%> In order to call a subroutine, we will use this kind of code: Whatever() Where Whatever is the name of the subroutine (it is recommended to use a very descriptive name of the task we want to perform within the subroutine to make it easier to understand the script). We may also provide information to the subroutine in order to perform the specified task. The data will be provided this way: Whatever(data1, data2 ... dataN)

In the following example we will provide different data to a unique subroutine depending on the Name of the person provided throw a form: Example 3 <% TheName=request.form("name)

1 2 3 if TheName="John" then 4 ResponseToVisitor(35,Sue,New York) 5 else 6 if TheName="Peter" then 7 ResponseToVisitor(33,Sally,Los Angeles) 8 else 9 response.write("Who are you?") 10 end if 11 end if 12 13 Sub ResponseToVisitor(AA,BB,CC) 14 response.write ("I know your are" & AA & "years old, 15 ") 16 response.write ("you are married to" & BB & ", and") 17 response.write ("you are living in " & CC) 18 End Sub 19 %> In line 14 it is specified AA is the first variable to be get, BB the second one, and CC the third one. The values for the three variables are provided in the same order in line 5 or line 8. The example above also shows subroutines are very useful to avoid repeating a specific number of tasks several times within the script, so that the script looks more organized and it is smaller.

Include/virtual Server Site includes or SSI is a very simple programing language (see a small tutorial) but it also has a very limited number of instructions. We will consider only one option SSI allows us to use within our asp scripts: include/virtual. In the next example we will use the include option of SSI in a our asp script (response.asp). This command allows as to add a set of instructions from different files (file1.txt and file2.txt bellow) and execute them. Example 4 response.asp <% TheName=request.form("name) if

TheName="John" then %> -->

I know your are 31 years old, you are married to Sue, and you are living in New York. File2.asp <% for i=1 to 3 response.write(Thename & "...
") next response.write("Who are you?") %>

In this case, if the name of the person who is visiting our page is John, then we will respond with file1.html. If not, then we will execute some asp instructions from file2.asp. The include file must be a text file (.txt, .html, .htm, .shtml, .asp...). Although we have used file1.html and file2.asp, the script will work exactly in the same way with file1.txt and file2.txt (changing the name of the files would have no effect).

By

using

SSI

and

asp

we

may

also

get

a

secret

page:

secret_page.asp Try ! <% UserName=request.form ("username") Password=request.form("password") if UserName="myusername" and Password="mypassword" then %> <% else %>
Username:
Password:
<% end if %> secret_info.txt This is my secret information:
My name is John.
My surname is Smith.

End of secret information. In this case it is convenient to save secret_info.txt file in the cgi-bin directory (the .txt file is not accessible by visitors from this directory, but it will be accessible from our top directory).

Session and Application and Include/virtual

In this page we will learn how to keep information from the user in our server (Session method) and how to share information between users (Application method). This is only a basic tutorial for beginners, so only basic features will be described. The Session method The first time a user accesses to a our pages some connections and disconnections took place. During this process the server and the client will interchange information to identify each other. Due to this exchange of information our server will be able to identify a specific user and this information may be use to assign specific information to each specific client. This relationship between computers is call a session. During the time a session is active, it is possible to assign information to a specific client by using Session method. We will use an example to explain this method: Let's suppose we want to allow specific user to access the information on our site or directory and we want to show a username in all pages visited by the user. In this case we may use the Session method. In

this

example,

we

will

ask

the

username

of

the

person

in

respondtoforms.asp <% IF Request.form="" THEN %>

1 2 3 4 Our private pages 5 In order to access this pages fill the form 6 7 below:
8
Username:
Password:
13 14
15 16 17 18 <% ELSE %> 19 20 <% 21 IF Request.form("username")="Joe" AND 22 Request.form("password")="please" THEN 23 %> 24 <% 25 Session("permission")="YES" 26 Session("username")="Joe" 27 %> 28 29

our

index.asp

page

Our <body><br /> <br /> private<br /> <br /> pages

30 Hi <% =Session("username") %>, you are allow to 31 32 see these pages:
33 Page 1
34 Page 2 35 36 37 38 39 <% ELSE %> 40 41 Error in username or password 42 <% END IF %> <% END IF %> Let's explain how this page works: In line 1 it is checked whether information is submitted throw a form. If the answer is negative (Request.form=""), a form is displayed asking for username and password. After filling the form and submitting it, as Request.form is not "" and the script will jump to line 15. In line 17 they are checked the username and password. If user name is "Joe" and Password is "please", then two variables are set for the client (lines 21-22): Session("permission")="YES" Session("username")="Joe" These variables will be kept in the server during the time the session is active (normally it will expire after 20 minutes without contact). Finally, if username and password are correct, a response page with links is send to the client with the name of the user in the top. In this example, if the username or password are incorrect the response page will include the text in line 38. Now, let's suppose the user clicks in the link "Page 1" (page1.asp). The code of page1.asp will be the following one:

page1.asp <% IF Session("permission")="YES" THEN %>

1 2 3 4 Page 1 5 6 7 Hi <% =Session("username") %>, welcome to Page 8 1
9 This page is empty at the moment, but it will be very 10 interesting in the next future 11 12

<% ELSE %> You are not allowed to access this page

13 14 15 16 17

<% end IF %> In line 1 it is check whether the value for Session("permission") is "YES". If the answer is positive a page with information is send to the client. If the answer is negative, the text in line 15 is send. NOTES:

• • •

Session method is suitable for sites with a limited number of visitors. For sites with a bigger number of visitors it is preferable to keep the information in the clients computer (by using cookies). To create more variables associated to a specific client we must substitute the text between brackets in Session("text"). The corresponding security features in the client's browser must be enable.

The Application method With Session method we have defined a value for Session("whatever")="Joe", but this information can not be share between visitors (Session("whatever") has a unique value for each visitor). To allow sharing information Application method is used. For a better understanding of this method we will create a counter which will be shown in the same page. In order to make it work, copy the code below to your server:

counter.asp <% Aplication.Lock Application("pagevisits")=Application("pagevisits")+1 Application.Unlock %> Page <body><br /> <br /> under<br /> <br /> construction

Under construction

Page views: <% =Application("pagevisits") %>

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

In the first part of this code, as Application method is shared between different clients, it is necessary to prevent other clients from modifying the information in Application("pagevisits"). Application.Lock will avoid that by stopping the information to be shared, and Application.Unlock will allow the information to be shared again. Line 3 increases the value for the counter. Finally a html code is send to the client, including the value of the counter. NOTES:



The information save as Application("whatever") as shown in this tutorial is lost each time the server is restarted.

Session and Application method has been used to create a simple chat script (copy and paste the code to your site and it will work immediately.

The

Dictionary

object

In order to learn how Dictionary object works we will create a small script which will translate number 1 to 10 from English to Spanish.

translate.asp <% SET MyDictionary=CreateObject("Scripting.Dictionary") MyDictionary.Add "one","uno" MyDictionary.Add "two","dos" MyDictionary.Add "three","tres" MyDictionary.Add "four","cuatro" MyDictionary.Add "five","cinco" MyDictionary.Add "six","seis" MyDictionary.Add "seven","siete" MyDictionary.Add "eight","ocho" MyDictionary.Add "nine","nueve" MyDictionary.Add "ten","diez" EnglishNumber="four" SpanishNumber=MyDictionary.Item (EnglishNumber) Response.Write(SpanishNumber) %>

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

How the script works

• •

• • •

Fist we have define a Dictionary named "Mydictionary" (line 2) We have add to the dictionary the data corresponding to the different number in English and Spanish (lines 4 to 13). When adding pairs of English and Spanish numbers to the Dictionary object, the number writen in English is a Key, and the number writen in Spanish a Item. In line 15 we have defined a variable named EnglishNumber and we have provided a value for this variable (in red). In line 16 we have defined a new variable (SpanishNumber) and we have get its value from the dictionary by indicating we want to get the Item corresponding to a specific Key (EnglishNumber). In line 17 the translated number is send to our visitor. The response will be "cuatro".

We may change the values in our dictionary by using this kind of code:

• •

MyDictionary.Key ("one")="1" example In our original script the key "one" will be substitute by a new key value ("1"). The item "uno" will not be changed. MyDictionary.Item ("two")="2" example In our original script the item corresponding to key "two" will be substitute by a new item value ("2"). The key "two" will not be changed.

We may display the number of element pairs in the dictyonary by using this code:



MyDictionary.Count example

If we want to check whether a key exists in our dictionary before responding to our visitor we will use this kind of comparisoncode if MyDictionary.Exists ("ten")=True then Response.Write("this key is included in the dictionary") lse Response.Write("Error: no such a key in the dictionary") end if Example: Translation of a number from English to Spanish This example uses most of the elements explained above.

• •

If there is no information posted to the script (line 6), the script will send to the visitor the form in the Sendform() subrouting (lines 34-40). When a request to translate a number is get the script will check whether the number corresponds to a key in the dictionary (line 25). If the response is afirmative the corresponding item is send to the visitor. In case the key does not exists, a "No translation available" response is send to the visitor (line 29). translation.asp try ! Page under construction

1 2 3 4 5 <% 6 if request.form="" then 7 Sendform() 8 else SET 9 10 MyDictionary=CreateObject("Scripting.Dictionary") 11 12 MyDictionary.Add "one","uno" 13 MyDictionary.Add "two","dos" 14 MyDictionary.Add "three","tres" 15 MyDictionary.Add "four","cuatro" 16 MyDictionary.Add "five","cinco" 17 MyDictionary.Add "six","seis" 18 MyDictionary.Add "seven","siete" 19 MyDictionary.Add "eight","ocho" 20 MyDictionary.Add "nine","nueve" 21 MyDictionary.Add "ten","diez" 22 EnglishNumber=request.form("EnglishNumber") 23 Response.Write("English number: " & 24 EnglishNumber) 25

if

MyDictionary.Exists

(EnglishNumber)=True

then

SpanishNumber=MyDictionary.Item (EnglishNumber) 26 Response.Write("
Spanish number: " & 27 SpanishNumber) 28 else 29 Response.Write("
Spanish number: " & 30 "No translation available") 31 end if 32 end if 33 %> 34 35 36 <% Sub Sendform() %> 37
38 Write a number in English

43
<% End Sub %>

Example: Password protected information In this example keys and items are used as usernames and passwords. It is very similar to the one above.

secretpage.asp try ! <% if request.form="" then Sendform() else SET MyDictionary=CreateObject("Scripting.Dictionary") MyDictionary.Add "John","123" MyDictionary.Add "Peter","456" MyDictionary.Add "Anna","789" Username=request.form("Username") Password=request.form("password")

1 2 3 4 5 6 7 8 9 10 11 12 if MyDictionary.Exists (Username)=True AND 13 14 Password=MyDictionary.Item (Username) then 15 SecretInfo() 16 else Response.Write("Error: incorrect userame or 17 18 password") 19 end if 20 end if 21 %> 22 23 <% Sub Sendform() %> 24

Username:
25 Password:
27 28
29 <% End Sub %> 30 31 32 <% Sub SecretInfo() %> 33 34 35 My Secret Page 36 37 38
39

This is my secret info

40 Hello !
41 Do you want to be my friend? 42
<% End Sub %>

Cookies method is very similar to Session method: the basic difference is that with Cookies method the information is save in the clients computer and not in the server, so it is more suitable for sites with a lot of visitors. This method implies sending information to the client and requesting it whenever the information is needed. Additionally, we will learn how to delete the information save in the clients computer when it is not necessary anymore. When the visitor gets to our asp file we may save information related with him in his computer. The order will be like this one: <% response.Cookies ("whatever")="information" %> When this line is executed, the visitor will have the information in his computer, and whenever we need that information, we may request it using this code: <% or <%

=request.Cookies

("whatever")

variable1=request.Cookies

("whatever")

%> %>

Let's try an example using Cookies method: let's consider we have visitors checking our site several times and we want to let them know how many times they have accessed to our computer.

cookiesexample.asp

try !

<% If Request.Cookies ("NumberVisits")="" Then %> <% Response.Cookies ("NumberVisits")=1 %> This is your first visit to this page. Welcome. <% Else %> <% VarNumberVisits=Request.Cookies

("NumberVisits") VarNumberVisits=VarNumberVisits+1 Response.Cookies("NumberVisits")=VarNumberVisits %>

<%

Welcome back to this page. You have visited this page =VarNumberVisits %> times.
Check my great links
.....
.....

<% End If %> Cookies method may be used to show visitors specific information we have requested throw a form, as for example a list of links related to a specific theme, information to allow access to the content of a page or to personalize the page (background color, frames or not frames...), information to fill a form automatically, etc.

Open and Read content from a text file Example

1:

This

one

1 2 3 4 5 6 7 8 9 10 11 12

will

be

the

basic

code

we

need

to

open

a

text

file:

<% Set fs = CreateObject("Scripting.FileSystemObject") Set wfile = fs.OpenTextFile("c:\Mydir\myfile.txt") filecontent = wfile.ReadAll wfile.close Set Set fs=nothing

wfile=nothing

response.write(filecontent) %>

Line 2 will create the appropriate environment which allows to perform the operations involving files in the server. We have defined a variable named "fs" to do it (we may change the name of this variable). In line 4 we have create a new variable named "wfile" and we have apply the method OpenTextFile to variable "fs". We have also define which is the exact location of the file we want to open in this line (the complete path is necessary). In line 5 we have read all the content of the file to a variable named "filecontent" using the instruction "ReadAll". Lines 7 to 9 are use to let the server know we have finished all operations involving files. In

line

11

we

have

response

to

the

client

with

the

content

in

the

variable

"filecontent".

Example 2: Let's suppose we have a file with different kind of information in each line (a name in the first line, the last name in the second one, and the age in the third one), and we want to use them separately. This

one

will

be

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

the

script

we

may

use:

<% Set fs = CreateObject("Scripting.FileSystemObject") Set wfile = fs.OpenTextFile("c:\Mydir\myfile.txt") firstname = wfile.ReadLine lastname = wfile.ReadLine theage = wfile.ReadLine wfile.close Set Set fs=nothing

wfile=nothing

%> Your first name is <% =firstname %>
Your last name is <% =firstname %>
Your are <% =firstname %> years old


This example is very similar to the previous one, but in this case each line we have read from "myfile.txt" has been saved to a different variable (lines 5 to 7), and they have been used in lines 15 to 17 to respond to the client. Example 3: This example will read all lines in the file, and the response page will include the content of each line with its line number.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

<% Set fs = CreateObject("Scripting.FileSystemObject") Set wfile = fs.OpenTextFile("c:\Mydir\myfile.txt") counter=0 do while not wfile.AtEndOfStream counter=counter+1 singleline=wfile.readline response.write (counter & singleline & "
") loop wfile.close Set Set fs=nothing

wfile=nothing

%>

In line 6 we will define the variable "counter", and in line 7 to 11 we will repeated instructions within the Do_While _Loop until the file does not reach the end of the file (the condition is "not wfile.AtEndOfStream"). Example 4: Let's suppose we have a file with a number in line 1 and a second number in line 2.

1 2 3 4

<% Set fs = CreateObject("Scripting.FileSystemObject")

5 6 7 8 9 10 11 12 13 14 15 16

Set wfile = fs.OpenTextFile("c:\Mydir\myfile.txt") number1 = Clng(wfile.ReadLine) number2= Clng(wfile.ReadLine) number1and2 = number1 response.write (number1and2) wfile.close Set Set fs=nothing

+

number2

wfile=nothing

%> In the previous examples we were able to save the value in a line to a variable, but that variable was a string class variable. In this example we have saved the content of line 1 and line 2 to variables "number1" and number2" by using the function "Clng". This function has allow us to add both numbers in line 9 and send the result to the client (line 10).

Create and Write a text file Example 1: The basic code we need to create a file is very similar to that one we have used to open a file:

1 2 3 4 5 6 7 8 9 10 11 12 13 14

<% thetext="Write this text in the file" Set fs = CreateObject("Scripting.FileSystemObject") Set wfile = fs.CreateTextFile("c:\Mydir\myfile.txt", True) wfile.Write (thetext) wfile.close Set Set fs=nothing

wfile=nothing

response.write("Text %>

created")

The differences to instructions when opening a file are line 6 and line 7: The method used in line 6 is "CreateTextFile"; it is necessary to indicate the complete path to the file we want to create; in line 6 we may use the instruction True (to allow over-writing an existing file) or False (if the file exits, it is not over-written). Line

7

will

write

in

the

file

the

string

We may also use this instruction to add content to the file wfile.WriteLine wfile.WriteLine ...

(thetext1) (thetext2)

in

variable

"thetext".

In this case we will write the content in variable "thetext1" in line 1, content in "thetext2" in line 2 etc.

Example 2: Let suppose we want to record the IP address of all visitor to our page to a file named "mylog.txt".

1 2 3 4 5 6 7 8 9 10 11 12 13 14

<% VisitorsIP=Request.ServerVariables ("REMOTE_ADDR") Set fs = CreateObject("Scripting.FileSystemObject") Set wfile = fs.OpenTextFile("c:\Mydir\mylog.txt", 8,false,0) wfile.WriteLine (VisitorsIP) wfile.close Set Set fs=nothing response.write("IP %>

wfile=nothing

registered")

The IP address is requested in line 2 (check Functions and Procedures). In this case we have open the file "mylog.txt" in line 6 with the instruction "forappending". this instruction will allow us to open the file and add at the end of it the IP address of our last visitor.

Global.asa is a text file locate in your main directory (/global.asa). Bellow is shown the basic extructure of a global.asa file. global.asa <SCRIPT LANGUAGE="VBScript" RUNAT="Server"> Sub ........ End Sub

Application_OnStart

Sub ........ End Sub

Application_OnEnd

Sub ........ End Sub

Session_OnStart

Sub ........ End Sub

Session_OnEnd

This file will be activated in this cases:

• •

When the first visitor accesses our pages When a new session starts.

In both cases, we may determine a series of events to be execute in the file above. 1. 2. 3. 4.

Application_OnStart It is execute before the first session is started. Application_OnEnd It is execute when the application is finished. Session_OnStart It is execute when the server creates a new session (when a new client acccesses our server). Session_OnEnd It is execute when a session is abandon of after certain period of time without contact between the client and the server (normaly after 20 minutes or so from the last request from a specific client, the server will consider he is not going to come back, so it will delete all the information related to that session).

Lets try a very simple example: Active Users Counter Just copy the code in the table to a text file and save it in the main directory of your site ("/global.asa").

global.asa <SCRIPT LANGUAGE="VBScript" RUNAT="Server">

1 2 Sub Application_OnStart 3 application("activevisitors")=0 4 End Sub 5 6 Sub Application_OnEnd 7 End Sub 8 9 10 Sub Session_OnStart 11 application.lock application("activevisitors")=application("activevisitors")+1 12 13 application.unlock 14 End Sub 15 16 Sub Session_OnEnd 17 application.lock 18 application("activevisitors")=application("activevisitors")-1 19 application.unlock 20 End Sub 21 22 The first time a visitor gets to our pages, global.asa will be executed, and consequently, application("activevisitors") in line 4 will get a value equal to "0". Immediately (as a new session has started), in line 12, application("activevisitors") will be increased by one. Each time a new visitor gets to our pages application("activevisitors") will be increased by one, and identically, each time a session is finished, this parameter will be reduce by one (line 18). In case we want to show the number of visitors in our page, we must use this kind of code :

In this tutorial we will create a regular HTML page with a small javascript code, and we will use this javascript code to include in the page new information from a ".asp" file. First,

let´s

check

this

two

pages:

javascript.html My page

1 2 3 4 <script language="javascript" 5 src="javascript.asp"> 6 7 8 javascript.asp document.write ("hello")

1

In the first file (javascript.html) we have include a javascript code in red, and within the code the file name from which we will get information to complete our page (src: source). So that we are asking for information to complete our page (javascript.html) to a different page (javascript.asp). This time we have only include the file name, but we may use the complete url even from a different site (for example: http://www.adifferentsite.com/javascript.asp). In the second file (javascript.asp) we have include the information necessary to write in the document the word "hello". This time we have use ".asp" extensión for the second page even though other extensions are possible. The

resulting

page

in

our

example

will

be

like

this

one:

javascript.html (resulting page) hello

So we already know we are able to include a text generated in one page within a different one. As the information we are including can be generate within a ".asp" file, we can add information dinamically by using Active Server Pages. Let´s try two examples: A very A simple text hit counter

rudimentary

banner

rotator

system

In case you are using ".asp" files whithin a site and the origen of the information we want to include in the page is originated in the same site, using any of those system is not very convenient: the number of conections to the server will increase, and there may be an important delay. In case you want to include information obtained from an asp script in several pages but you do not want to copy the asp script in all of them, you may use the Include instruction, so that the script is only in one page, and by changing it you will change the results in several pages. A very rudimentary banner rotator system

Our page is "mypage.html" and we are requesting information to complete it from "http://www.myadrotator.com/adrotator.asp" which may be located in the same or in a different site. The information provided by the second file will determinate the ad to be display in our page.

mypage.html My page

1 2 3 4 <script language="javascript" 5 src="http://www.myadrotator.com/adrotator.asp"> 6 7 8

ARRAYS Introduction Working with Arrays Filtering values from a array Creating a table from data in a string Simple keyword search Introduction Instead of having our information (variables or numbers) in variables like Mydata1, Mydata2, Mydata3 etc, by using arrays our information will be in an unique variable. Let´s check an example:

array.asp My Array <% DIM MyData(2,2) MyData (0,0) = MyData (0,1) = MyData (0,2) = MyData (1,0) = MyData (1,1) = MyData (1,2) = MyData (2,0) = MyData (2,1) = MyData (2,2) = "9"

"1" "2" "3" "4" "5" "6" "7" "8"

1 2 3 4 5 6 7 8 9 10 11 12 13

Response.write (MyData (1,2)) 14 %>

Line 6: In this example we have defined by using "DIM" an array named Mydata and we have defined the size of the array. We may consider the table bellow as the source of information for our array. MyData

0

1

2

0

1

2

3

1

4

5

6

2

7

8

9

15 Lines 7-15. After defining the array we 16 have assigned values to

the array. 17 18 19 20 21

Line 17. In the response page we will send the value assigned to MyData(1,2) in the array. The first number will be the row and the second the column, so that in our case the response page will show the value "6"

Very often, we will defined an array from data obtained from a table with only one column. Let´s check an example:

array2.asp My Array <% DIM MyData(9) MyData (0) = MyData (1) = MyData (2) = MyData (3) = MyData (4) = MyData (5) = MyData (6) = MyData (7) = MyData (8) = MyData (9) = "9"

"0" "1" "2" "3" "4" "5" "6" "7" "8"

Response.write (MyData (5)) %>

1 Original table for the 2 array in the script 3 4 MyData 5 6 0 1 7 8 1 4 9 10 2 7 11

3

3

4

4

13

5

5

14

6

6

15

7

7

16

8

8

17

9

9

12

In the response page we will 18 send the value 19 assigned to MyData(5) in the array. The response page will 20 return 5. 21 It is also possible to define an array with more dimensions as for example MyData(5,5,5,5). Working with Arrays In the examples above we have defined all the values within the script one by one, but this assignation may be done in a different way, as it is described in the example bellow:

array3a.asp

Resulting page

<pre> <% MyArray=Array(Zero,one,two,three, four,five,six,seven,eight,nine) %>

Thearray(0): Thearray(1): Thearray(2): Thearray(3): Thearray(4): Thearray(5): Thearray(6): Thearray(7): Thearray(8): Thearray(9):

Thearray(0): Thearray(1): Thearray(2): Thearray(3): Thearray(4): Thearray(5): Thearray(6): Thearray(7): Thearray(8): Thearray(9):

<% <% <% <% <% <% <% <% <% <%

=Thearray(0) %> =Thearray(1) %> =Thearray(2) %> =Thearray(3) %> =Thearray(4) %> =Thearray(5) %> =Thearray(6) %> =Thearray(7) %> =Thearray(8) %> =Thearray(9) %>

Zero pne two three four five six seven eight nine

In this example the array has been create from a string, and each component of the array has been separated by a comma. The Array method will do it for us easily. We may also want to use a different string with a different delimiter to define the components in our array:

array3b.asp

Resulting page

<pre> <% TheText="Zero=one=two=three= four=five=six=seven=eight=nine" Thearray=split (TheText,"=") %> Thearray(0): Thearray(1): Thearray(2): Thearray(3): Thearray(4): Thearray(5): Thearray(6): Thearray(7): Thearray(8): Thearray(9):

Thearray(0): Thearray(1): Thearray(2): Thearray(3): Thearray(4): Thearray(5): Thearray(6): <% =Thearray(0) %> Thearray(7): <% =Thearray(1) %> Thearray(8): <% =Thearray(2) %> Thearray(9): <% =Thearray(3) %> <% =Thearray(4) %> <% =Thearray(5) %> <% =Thearray(6) %> <% =Thearray(7) %> <% =Thearray(8) %> <% =Thearray(9) %>

Zero pne two three four five six seven eight nine

In this example we have defined the variable TheText, and whithin this variable we have include strings separated by "=". In the next line, we have split the variable TheText into an array of strings (Thearray). Split command have been used to brake TheText and "=" has been used as a delimiter to separate the substrings. In

the

response

page

we

have

indicated

the

individual

values

of

Thearray

one

by

one.

It may happend to have a variable we want to split, but we do not know how many substrings we may get. In that case we may use ubound command to discover how many elements are in our array, and them we may use that value to write them by using a For-next loop (see example below).

array4.asp

Resulting page

<pre> <% TheText="a,f,w,d,u,t,e,u,f,v,o" Thearray=split (TheText,"=") %>

How many Strings do I have in TheArray? 10

How many String do I have in TheArray? a <% =ubound(Thearray)+1 %> f w d <% u For n=0 to ubound(Thearray) Response.write (Thearray(n) & "
") t e next u %> f v o

Filtering values from a array In the next example we will filter the information in our array, and we will display only part of it.

array5.asp <pre> <% dim MyArray(9) MyArray (0) = "Zero" MyArray (1) = "One" MyArray (2) = "Two" MyArray (3) = "Three" MyArray (4) = "Four" MyArray (5) = "Five" MyArray (6) = "Six" MyArray (7) = "Seven" MyArray (8) = "Eight" MyArray (9) = "Nine" %>

Find strings containing "t" (case sensitive) <% =join(filter(MyArray,"t",True,0),",") %> Find strings containing "t" <% =join(filter(MyArray,"t",True,1),",") %> Find strings which do not contain "t" (case sensitive) <% =join(filter(MyArray,"t",False,0),",") %> Find strings which do not contain "t" <% =join(filter(MyArray,"t",False,1),",") %> Find strings containing "t" (case sensitive)

Eight Find strings containing "t" Two,Three,Eight Find strings which do not contain "t" (case sensitive) Zero,One,Two,Three,Four,Five,Six,Seven,Nine Find strings which do not contain "t" Zero,One,Four,Five,Six,Seven,Nine The array and the assignation of values has been done as usually, and in the second part of the script we have used some lines similar to this one: <% =join(filter(MyArray,"t",True,0),",") %> In

this

lines

we

have

filter

the

values

at

MyArray

and

we

have

join

them.

filter(MyArray,"t",True,0) This part of the line have search for "t" in MyArray. True means we have selected the strings containing the search string (in this case "t"). False will indicate we are selecting the strings which do not content the search string. 0 means our search is case sensitive (a binary comparation) 1 will mean it is not a case sensitive search (a textual comparation) join(filter(MyArray,"t",True,0),",") The complete line will join the filtered strings with the delimiter indicated (in this case ",") Creating a table from data in a string In order to undertand this script we will consider we have a table like the one bellow, and that this table was the original source of information we used to create our table:

Peter student

Chicago 123

John teacher

London 234

Sue

Manager Sidney

789

From the table we got this three lines by separeting the values by commas: Peter,student,Chicago,123 John,teacher,London,234 Sue,Manager,Sidney,789 And finaly we conected the three lines by separeting the values with "/": Peter,student,Chicago,123/John,teacher,London, 234/Sue,Manager,Sidney,789 The string obtained was saved to a variable named Mydata in the script bellow. The resulting page will show a table like the original. This script is not limited by number of rows or columns (the maximun amount of then is calculate each time we run the script).

Createatable.asp <% Mydata="Peter,student,Chicago,123/John,teacher, London,234/Sue,Manager,Sidney,789" Createtable() %>

<% Sub CreateTable() MyRows=split (Mydata,"/") RowsNumber=ubound(MyRows) Response.write ("") For i=0 to RowsNumber DatainRow=split (MyRows(i),",") NumberofDatainRow=ubound(DatainRow) Response.write ("") For n=0 to NumberofDatainRow Response.write("") Next Response.write ("") Next Response.write ("
" & DatainRow(n) & "
") End %>

Sub

This script may be used for several porpouses: we may generate Mydata by filtering values from an array as shown bellow: <% Dim Myclients(3) Myclients(0)="Peter Smith,Chicago,Manager,123" Myclients(1)="John Smith,New York,Accountant,124" Myclients(2)="George Smith,Chicago,Administration,245" Myclients(3)="Sam Smith,Dallas,Consultant,567" SearchFor="Chicago" Mydata=join(filter(Myclients,SearchFor,True,1),"/") Createtable() %>

This code in combination with Createtable() Subroutine in the previus example will display only the clients from Chicago. The SearchFor variable may be obtained from a form.

Simple keyword search In this example, in our first visit a form asking for a keyword will be display. After submitting the keyword Toredirect() Subroutine will be activated. In this Subroutine we have create two arrays: Myinfo has a description of the URL located at MyURL. In case the keyword is included in the description of the site, the visitor will be redirected to the corresponding URL. Both arrays may be very very long.

search.asp <% if request.form="" them %>

<% else Toredirect() end if %> <% Sub Toredirect() dim Myinfo(4) Myinfo (0) = "Asp tutorial for beginners" Myinfo (1) = "Displaying Date Time and Text" Myinfo (2) = "Using Variables and Forms" Myinfo (3) = "If...Then and For...Next instructions" Myinfo (4) = "Do...Loop and Select...Case instructions" dim MyURL(4) MyURL (0) = "http://www.asptutorial.info" MyURL (1) = "http://www.asptutorial.info/Datetime.htm" MyURL (2) = "http://www.asptutorial.info/Forms.htm" MyURL (3) = "http://www.asptutorial.info/if_thenfor_next.htm" MyURL (4) = "http://www.asptutorial.info/Do_loopSelect_case.htm" Numberofpairs=ubound(Myinfo) For n=0 to Numberofpairs if inStr(Myinfo (n), request.form ("keyword"))>0 then Response.redirect(MyURL(n)) end if Next Response.write ("The keyword has not been found") End Sub %>

ASP file as a picture source

We are trying this tutorial to be simple, so in this page we will request imagenes from a ".asp" page, but the imagen will not be newly generated. The images will be already saved in our server . First,

let´s

check

this

two

pages:

showpicture.html My picture

1 2 3 4 5 6 7 8

mypicture.asp <% response.ContentType ="image/GIF" %>

• •

1 2

In the first file (showpicture.html) we have include in the html code the source for our picture ("mypicture.asp", instead of "mypicture.gif"). In the response page, first we have indicated whith kind of ContentType we are sending to the client (this time "image/GIF", and then by using "include/virtual" the file is send (in this case all files are in the same directory)

Let´s

try

an

examples:

A rudimentary banner rotator system Our page is "mypage.html" and we are requesting a picture to a file named "mypicture.asp". This file will send to the client one of the pictures available (in this case up to 5), and two variables will be set up:

• •

session ("ad"): will be used to save a number, which is needed to determinate which ad to show each time session ("linkto"): will be used to save the link corresponding to the ad shown. mypage.html My page

1 2 3 4 src=mypicture.asp 5 6 7 8

mypictureasp <% if session("ad")="" then session("ad")=0 end if if else

session("ad")=5 session("ad")=1

then

session("ad")=session("ad")+1

end if response.ContentType

="image/GIF"

1 2 3 4 5 6 7 8 9 10 11 12 13

%> <% <%

Select

Case session("ad") %> case 1 session("linkto")="http://linkto1.com" %> <% case 2 session("linkto")="http://linkto2.com" %> <% case 3 session("linkto")="http://linkto3.com" %> <% case 4 session("linkto")="http://linkto4.com" %> <% case 5 session("linkto")="http://linkto5.com" %> <% End select %>

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

adrotatorlink.asp response.redirect(session("linkto"))

1

"mypage.html" At "mypage.html" we have include the regular HTML code to show a picture. We have used within the code the instruction "NOSAVE", so the picture will not be saved in the clients cache.

"mypicture.asp"

• • • •

Lines 2-3. Each time a new visitor gets to "http://www.myadrotator.com/adrotator.asp" a new session will be open, and by using the session method, we will define session("ad") value to 0. In case the visitor is not new, the value for session("ad") will exits, and that value will be keep. Lines 6-10. The value for Session("ad") is increased by one unless that value is 5 (which is the maximum value allowed in this script) Line 12. The ContentType is defined Lines 15-31. By using Select_case and depending on the value saved in the instruction session("ad"), we will define session("linkto"), which will be the url to which we will redirect our visitor in case the picture send to the browser is clicked.

"adrotatorlink.asp" After clicking the corresponding picture, and as we have already save the corresponding URL at session('linkto"), we will redirect the visitor to the correct URL. NOTE: By using "NOSAVE" code in our page, the client will no save the picture in the cache of the computer. It may be a problem for us: let´s suppose we have include this the same code in several pages within our site. Each time we visit a new page, session ("linkto") will be defined again, but in case the visitor clicks the back bottom of the browser and the picture show is the same one it was shown in our previous visit, when clicking the visitor will be redirect to a non-correct URL.

Active Server Pages Server-Side Scripting abs (n: number) Function. Returns the absolute value of n.

chr (asciicharcode: number) Function. Returns a string containing the ASCII character specified by asciicharcode. For a list of ASCII characters and http://www.microsoft.com/workshop/author/newhtml/htmlr018.htm.

character

codes,

see

date Function. Returns the current system date as a string. day (thedate: string) Function. Extracts the day of the month from thedate and returns it as a number. hour (thetime: string) Function. Extracts the hour value from thetime and returns it as a number. left (thestring: string, n: number) Function. Returns a string containing the first n characters of thestring. len (thestring: string) Function. Returns the number of characters in thestring. minute (thetime: string) Function. Extracts the minutes value from thetime and returns it as a number. month (thedate: string) Function. Extracts the month value from thedate and returns it as a number. monthname (themonth: number) Function. Returns a string containing the name of the month whose number is specified by themonth. now Function. Returns the current system date and time. Request.Form (fieldname: string) Function. Returns the contents of the field whose name is fieldname. ServerVariables Request.ServerVariables ("HTTP_User-Agent") Function. Returns the client browser type as a string. Request.ServerVariables ("REMOTE_ADDR") Function. Returns the client's IP (Internet protocol) address as a string. Request.ServerVariables ("REMOTE_HOST") Function. Returns the client's domain name as a string. Request.ServerVariables ("SERVER_NAME") Function. Returns the domain name of the server as a string. If the server has no domain name, returns the server's IP address as a string. Additional ServerVariables Response.redirect (anotherURL: string) Procedure. Redirects the current request to one specified by anotherURL.

right (thestring: string, n: number) Function. Returns a string containing the last n characters of thestring. second (thetime: string) Function. Extracts the seconds value from thetime and returns it as a number. Server.URLEncode (thestring: string) Function. Converts thestring from a string to a URL by "escaping" certain characters. For example, each space character is replaced with %20. Returns the URL. time Function. Returns the current system time as a string. timevalue (thetime: string) Function. Extracts the time value from thetime and returns it as a string.

weekday (thedate: string) Function. Extracts the weekday value from thedate and returns it as a number. weekdayname (weekday: number) Function. Returns a string containing the name of the weekday whose number is specified by weekday. year (thedate: string) Function. Extracts the year value from thedate and returns it as a number. Operators The following operators are supported in ASP server-side scripts:

• • • • • • • • • • • • • • • • • • • •

Addition (+) And Assignment (=) Concatenation (&) Division (/) Exponentiation (^) Is Equals (=) Greater Than (>) Greater Than or Equal to (>=) Less Than (>) Less Than or Equal to (>=) Mod Multiplication (*) Negation (-) Not Not Equal To (<>) Or Subtraction (-) Xor

Related Documents

Asp Tutorial
July 2020 2
Asp Tutorial
November 2019 3
Asp Tutorial
November 2019 7
Asp Tutorial
November 2019 2
Tutorial Asp
November 2019 8