Você está na página 1de 93

ASPDica1.

doc Página 1 de 93

Active Server Pages (ASP) é uma linguagem para geração de páginas HTML
dinamicamente.
A partir de um Windows NT Server com o IIS3 ou IIS4 (Internet Information Server)
instalado, é possível rodar códigos que geram páginas HTML dinamicamente, e então,
mandá-las para o Browser. Assim sendo, sempre que uma página ASP for requisitada pelo
Browser, esta página será executada pelo servidor, e a partir daí, será gerada uma página
HTML, a qual será enviada para o Browser que a requisitou.
É possível então, a partir de uma única rotina, gerar uma página HTML contendo os
registros ,de um banco de dados, cujo o nome começa com a letra A. Ou então gerar uma
página HTML contendo todos os registros cuja cidade é Fortaleza.
Detalhando um pouco mais o exemplo acima, um usuário qualquer entra na página
principal da agenda virtual da sua empresa. Nesta página existem links para todas as letras
do alfabeto e para todas as cidades listadas na agenda. Esse usuário clica no link na letra A
(poderia ser de qualquer outra letra), e então uma página ASP (uma rotina ASP) é acionada
no servidor. O servidor por sua vez, vai ler e executar esta página, o que significa que, em
primeiro lugar, o servidor abrirá o banco de dados, ai então, fará uma consulta a este banco
de dados requisitando todos os registros cujo nome comece com a letra A. Aí então o
servidor cria uma página HTML contendo todos esses registros numa tabela.
A linguagem ASP não serve apenas para consultas a banco de dados. Serve também para
envio e recebimento de correio eletrônico via páginas HTML, para criação rotinas de
propaganda rotativa, para identificação e autenticação de usuários, para leitura de arquivos
texto e uma infinidade de outras aplicações.
www.aspbrasil.com.br
Como rodar páginas ASP em um micro com Windows 95/98
A Microsoft disponibiliza, gratuitamente, o programa PWS (Personal Web Server).
O PWS é um servidor de páginas WEB local, ou seja, só pode ser acessado pelo próprio micro. Ele
processa páginas ASP, o que possibilita o programador de testar as páginas em ASP antes de
colocá-las online.
O PWS pode ser encontrado no site da Microsoft, ou no CD do Windows 98. Futuramente, ele
estará disponível para download aqui no site ASPBRASIL.
A instalação do PWS é muito simples. Como todos os programas da Microsoft, ele contém
assistentes (wizards) que o auxiliam na instalação e configuração do PWS.
Para acessar as páginas ASP, basta usar um browser. A diferença é que ao invés de se colocar o
endereço físico da página (e:\teste\testes.asp) utiliza-se o endereço virtual
(localhost/teste/testes.asp).
Ao instalar o PWS, um diretório padrão, chamado c:\inetpub\ é criado e habilitado para acesso.
Isso significa que todos os arquivos e pastas dentro desta pasta podem ser acessadas via PWS,
apenas digitando o endereço virtual. Mas é possível habilitar outros diretórios para serem
acessados via PWS. Desse modo, o uso do PWS não fica restrito ao diretório Inetpub. Basta seguir
os passos abaixo:
1. Abrir o Microsoft Explorer
2. Clicar com o botão direito sobre a pasta que deseja habilitar
3. Clicar em Compartilhamento
4. Clicar em WebSharing
5. Selecionar Share this folder
6. Denominar um nome virtual para este diretório

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 2 de 93

Por exemplo, se o diretório que se pretende habilitar tem o endereço físico


c:\teste\includefile\temporario\, é possível designar o nome virtual como includetemporario, e a
partir daí, o acesso a esse diretório será: localhost/includetemporario/nomedoarquivo.asp

Rodando ASP fora do Ambiente WINDOWS


Duas empresas americanas desenvolveram produtos que permitem o processamento de rotinas
ASP em servidores não-Microsoft, são elas a Chili!Soft e a Halcyon Software.
O produto da Chili!soft (www.chilisoft.com), denominado Chili!Soft ASP, permite que rotinas ASP
sejam processadas nas plataformas UNIX, NT, LINUX e outros. Já o software da Halcyon
(www.halcyonsoft.com), denominado Instant ASP, atende aos servidores UNIX, LINUX, SOLARIS,
SGI, NOVELL, WINNT, Netscape Enterprise Server entre outros.
A Chili!soft disponibiliza o Chili!Soft ASP para download em três versões, a Trial (30 dias full-
functions), a versão Developer Edition (sem limite de tempo, mas com limite de 5 sessões de
usuários concomitantemente), e a versão Full, disponível para compra. O Instant ASP pode ser
baixado da rede em duas versões, Developer Version e a Full Version, esta última disponível para
compra.

A linguagem ASP é, na verdade, uma junção de programação em VBScript e Objetos ActiveX.


VBScript é uma linguagem criada a partir do Visual Basic, mas com algumas limitações, por
motivos de segurança.
Objetos ActiveX são objetos, ou melhor, funções prontas, já existentes no servidor. Essas funções
captam os parâmetros de entrada dos dados, manipula-os de acordo a sua função e então envia-
os para a saída. Um exemplo de ActiveX é o Objeto ASPMail, o qual capta os dados de entrada
(nome, email, corpo da mensagem, etc), cria um email com esses dados e depois envia o email.
Uma vez que a linguagem ASP é usada apenas em alguns "pedaços" de páginas HTML, existe um
símbolo para diferenciar o que é programação HTML e o que é programação ASP: <% código asp
%>
Abaixo um exemplo de página em HTML e ASP:
<head>
<title>página em HTML e ASP</title>
</head>
<html>
<p>Olá Mundo!!!</p>
<%
' (aspas simples significa observação dentro do código)
' a linha abaixo tem o mesmo efeito da linha acima
response.write "<p>Olá Mundo</p>"
%>
</html>

Funcionamento, Convenção e Simbologia


Como Funciona o ASP? Qual a simbologia e a convenção usada na programação em ASP?
ASP é uma linguagem que veio para complementar a linguagem HTML. Ela traz para a linguagem
HTML todo o poder do acesso a banco de dados, do acesso a arquivos texto, da captação de
informações de formulário, da captação de informações sobre o visitante e sobre o servidor, do uso
de variáveis, loops. Observe o código abaixo:
arquivo "olamundo.asp"
<html>
<head><title>Como funciona o ASP?</title></head>
<body bgcolor="#FFFFFF">
<p>Ola Mundo!!!</p>
<%
response.write "<p>Ola Mundo!!!</p>"
%>
<p><%="Ola Mundo!!!"%></p>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 3 de 93

</body></html>

O Objeto Response
O objeto Response se refere a todos os dados enviados do servidor para o cliente (usuário -
browser), ou seja, qualquer informação enviada do servidor para o browser do usuário se utiliza do
objeto Response.
Funções do Objeto Response:
response.write - permite enviar texto ao browser
response.redirect - Redireciona o browser para um endereço especificado.
response.buffer - avisa o browser do usuário que a página só deverá ser mostrada após ser
totalmente carregada. É interessante para usar com a função response.redirect.
response.cookies - grava informações no cookie do browser

response.write - envia textos ao browser. É interessante na construção de textos que mixam


textos prontos e variáveis.
sintaxe: response.write texto/variável
<html>
<head>
<title>response.asp</title>
</head>
<body bgcolor="#FFFFFF">
<%
response.write "Olá!!! Abaixo uma rotina com o objeto response.write cujo texto varia de acordo com a
variável counter"
for counter=1 to 5000
response.write counter & "->"
next
%>
</body>
</html>

response.redirect - redireciona o browser do usuário para a página especificada.


Esta função só pode ser usada antes do browser divulgar alguma informação na
tela.
sintaxe: response.redirect(URL)
<%
'A função response.redirect redireciona o browser do cliente para o endereço contido na variável
URLnova, no caso, www.aspbrasil.com.br
URLnova = "http://www.aspbrasil.com.br/"
response.redirect(URLnova)
%>
<html>
<head>
<title>response.asp</title>
</head>
<body bgcolor="#FFFFFF">
</body>
</html>

response.buffer - avisa o browser do usuário que a página só deverá ser


mostrada após ser totalmente carregada. É interessante para usar com a função
response.redirect. Observe o exemplo:
sintaxe: response.buffer = true/false
<%

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 4 de 93

response.buffer = true
%>
< html>
< head>
< title> response.asp< /title>
</head>
<body>
<%
response.write "Olá denovo!!! Abaixo o uso da função response.buffer, a qual, quando tiver o valor
true, avisa o browser para mostrar as informações só depois de totalmente carregadas. Isto permite que
haja um response.redirect em qualquer parte da página. Mas quando tiver o valor false, o browser
mostra as informações assim que elas vão chegando."
response.redirect "http://www.aspbrasil.com.br/"
%>
</body>
</html>

response.cookies - grava informações no cookie do browser.


<html>
<head><title>cookies</title></head>
<body>
<%
'o comando time insere o horário atual do servidor
response.cookies("aspbrasil")("horariovisita") = time
%>
</body></html>

Objeto Request
O objeto Request se refere a todos os dados requisitados pelo servidor ao cliente, ou seja,
qualquer informação requisitada pelo servidor ao browser do usuário.
Funções do Objeto Request:
request.form - recupera valores de variáveis enviadas via formulário pelo método post.
request.QueryString - recurepa valores de variáveis enviadas via formulário pelo método get.
request.servervariables - recupera informações sobre o browser do usuário e sobre o servidor
WEB.
request.cookies - recupera informações do cookie do browser do usuário.
request.ClientCertificate - mostra informações sobre o certificado de segurança do usuário.
Somente é usado em sites com transmissão segura de dados (https)
exemplos:
request.form - recupera valores de variáveis enviadas via formulário pelo método post.
sintaxe: request.form("nomedavariavel") ou simplesmente request("nomedavariavel")
Abaixo, formulário de cadastramento.
<html><head><title>Formulário</title></head>
<body>
<form method="post" action="retrieve.asp">
<div>Nome: </div><input type="text" name="nome">
<div>Endereço: </div><input type="text" name="endereco">
<input type="submit" value="enviar">
</body>
</html>
a seguir, a rotina de recuperação destes dados preenchidos (nome e endereço)
<html><head><title>Recuperação dos dados</title></head>
<body>
<div>Abaixo, nome e endereço do usuário que preencheu o formulário: </div>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 5 de 93

<%
response.write "<div>Nome: </div>" & request.form("nome")
response.write "<div>Endereço: </div>" & request.form("endereco")
%>
</body></html>
clique aqui para rodar a rotina acima
request.QueryString - recupera valores de variáveis enviadas via formulário pelo método get.
sintaxe: request.querystring("nomedavariavel") ou, também, simplesmente
request("nomedavariavel")
Abaixo, formulário de cadastramento.
<html><head><title>Formulário</title></head>
<body>
<form method="get" action="retrieve.asp">
<div>Nome: </div><input type="text" name="nome">
<div>Endereço: </div><input type="text" name="endereco">
<input type="submit" value="enviar">
</body>
</html>
a seguir, a rotina de recuperação destes dados preenchidos (nome e endereço)
<html><head><title>Recuperação dos dados</title></head>
<body>
<div>Abaixo, nome e endereço do usuário que preencheu o formulário: </div>
<%
response.write "<div>Nome: </div>" & request.form("nome")
response.write "<div>Endereço: </div>" & request.form("endereco")
%>
</body></html>
clique aqui para rodar a rotina acima
request.servervariables - recupera informações sobre o browser do usuário e sobre o servidor
WEB.
sintaxe: request.servervariables("valorsolicitado")
Abaixo um exemplo de como conseguir alguns valores do Browser do usuário
<html><head><title>Server Variables</title></head>
<body>
<%
response.write "<div>" & request.Servervariables("remote_Addr") & "</div>"
response.write "<div>" & request.Servervariables("server_name") & "</div>"
'request.servervariables("remote_addr") busca o IP remoto do usuário
'request.servervariables("server_name") busca o nome ou IP do servidor
%>
</body></html>
clique aqui para rodar a rotina acima
request.cookies - recupera informações do cookie do browser do usuário.
sintaxe: request.cookies("nomedocookie")("parâmetrodocookie")
Abaixo, rotina que adiciona (response.cookies) e que recupera (request.cookies) informações do
cookie
<html><head><title>Server Variables</title></head>
<body>
<%
'a função time retorna o horário do servidor
response.cookies("aspbrasil")("horavisita") = time
'acima, rotina de criação de cookie
response.write "<div>" & request.cookies("aspbrasil")("horavisita") & "</div>"
'acima, rotina de recuperação da informação colocada no cookie de nome aspbrasil
%>
</body></html>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 6 de 93

request.ClientCertificate - mostra informações sobre o certificado de segurança do usuário.


Somente é usado em sites com transmissão segura de dados (https).
sintaxe: request.clientcertificate(parâmetro[sub-parâmetro])
abaixo, exemplo de recuperação de informações sobre um site seguro.
<html><head><title>Server Variables</title></head>
<body>
<%
reponse.write "<div>" & response.clientcertificate("validfrom") & "</div>"
'retorna a data inicial da validade do certificado
%>
</body></html>

objeto Server
objeto Server permite o acesso e a configuração de algumas funções e métodos diretamente
ligados ao servidor.
Funções do Objeto Server:
server.ScriptTimeOut - configuração do Timeout de carregamento da página
server.HTMLEncode - codifica strings. Usado para codificar strings que contenham caracteres
especiais.
server.URLEncode - transforma strings para o formato QueryString.
server.MapPath - mapeia arquivos de acordo com o path físico, a partir do path virtual.
server.CreatObject - permite abertura de instâncias de objetos vinculados a componentes ActiveX.
exemplos:
server.ScriptTimeOut - Configura o tempo máximo para execução e carregamento da página. O
tempo padrão é de 90 segundos.
sintaxe: server.ScriptTimeOut = tempo
<html><head><title>Testando ScriptTimeOut</title></head>
<body>
<%
response.write(server.scriptTimeOut & "<BR>")
Server.ScriptTimeOut = 120
response.write(server.ScriptTimeOut & "<br>")
%>
</body></html>
clique aqui para rodar a rotina acima
server.HTMLEncode - usa-se para codificar textos que contenham caracteres especiais, tais como
> ou <. Codificado, o Browser saberá que o caractere faz parte do texto, e então, este caractere
não será interpretado com código. É usado também para para codificar caracteres de outros
idiomas, de forma que o Browser identifique o idioma, e então exponha os símbolos corretos na
tela.
sintaxe: server.HTMLEncode("string")
<html><head><title>HTML Enconde</title></head>
<body>
<%
response.write(server.HTMLEncode("<<<Olá Mundo>>>"))
response.write(server.HTMLEncode("WELCOME TO MÜNCHEN"))
'os caracteres <, >, e Ü são caracteres especiais. O comando HTMLEncode assegura que
esses códigos serão interpretados de forma correta pelo Browser.
%>
</body>
</html>
clique aqui para rodar a rotina acima
server.URLEncode - URLs (Uniform Resource Locators) são usados para requisitar arquivos e
informações em servidores WEB. Muitas vezes, os URLs não contém apenas o nome do arquivo,

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 7 de 93

mas também carregam com eles valores de variáveis no formato QueryString. O comando
server.URLEncode transforma strings de texto em strings no formato QueryString.
sintaxe: request.URLEncode("string")
<html><head><title>HTML Enconde</title></head>
<body>
<%
response.write(server.URLEncode("test.asp?name= Fernando Medeiros&idade=25 anos"))
response.write("test.asp?" & server.URLEncode("name= Fernando Medeiros&idade=25
anos"))
%>
</body>
</html>
clique aqui para rodar a rotina acima
server.MapPath - retorna o path físico do arquivo a partir do path virtual.No caso de arquivos que
não tenham homônimos no mesmo domínio, a função server.MapPath é capaz de localizar o
arquivo no domínio e retornar o path físico.
sintaxe: server.MapPath("path virtual")
<html><head><title>server.MapPath</title></head>
<body>
<%
response.write(server.mappath("/test.asp"))
'a linha acima retorna o path físico do arquivo test.asp no servidor. No caso,
c:\aspbrasil\test.asp
response.write(server.MapPath("test.asp"))
'a linha acima retorna o mesmo path físico, apesar de não conter o path virtual, e sim,
apenas o nome do arquivo. Tal retorno só é possível se não existirem dois arquivos com o
mesmo nome dentro do mesmo domínio.
%>
</body></html>
clique aqui para rodar a rotina acima
server.CreateObject - É usado para gerar instâncias de componentes para uso nos Scripts. Por
padrão, cada objeto criado a partir do componente é automaticamente destruído ao acabar o
processamento da página.
sintaxe: Set nomedadoaoobjeto = Server.CreateObject("iddoobjeto")
<html><head><title>Create Object</title></head>
<body>
<%
Set objtexto = Server.CreateObject("Scripting.FileSystemObject")
'a linha acima criou uma instância de objeto do componente scripting.filesystemobject,
usado para acessar arquivos texto.
Set arquivotexto = objtexto.OpenTextFile(Server.MapPath("test.txt"))
'abre o arquivo texto dentro da instância do objeto Scripting.FileSystemObject
response.write arquivotexto.readline
'a linha acima mostra a primeira linha de texto do arquivo aberto.
arquivotexto.close
'a linha abaixo destruíu imediatamente
%>
</body></html>
clique aqui para rodar a rotina acima

Componente FileAccess
O componente File Access é um componente usado para acessar arquivos texto. Os arquivos tipo
texto, muitas vezes, são usados como banco de dados de acesso sequencial (nem sempre é
vantagem se usar bancos de dados com acesso aleatório, como o MSAccess, ...). Assim sendo, foi
necessário a criação de um componente que permitisse a leitura e gravação de dados nestes
arquivos.

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 8 de 93

sintaxe:
conexão com o componente: Set fsObj = Server.CreateObject("Scripting.FileSystemObject")
criação do arquivo test.txt: Set txtStreamObj = fsObj.CreateTextFile(name,[bOverWrite])
abertura do arquivo test.txt para leitura ou gravação: Set txtStreamObj = fsObj.OpenTextFile(name,
[iomode,[bCreate,[format]]])
fsObj, txtStreamObj são variáveis definidas pelo usuário.
name - nome do arquivo texto (colocar o path caso o arquivo se localize em outra pasta que não a
do arquivo ASP que possui este código)
bOverWrite - TRUE: caso o arquivo existe, ele é deletado, e um novo é criado. FALSE: caso o
arquivo exista, ele não é substituído.
iomode - FROWRITING, FORREADING: modo de abertura do arquivo selecionado (para gravação,
para leitura)
bCreate - TRUE: caso o arquivo selecionado para abertura não exista, ele é criado.
format - TRUE: é criado um arquivo texto usando o formato Unicode. FALSE: é criado um arquivo
texto usando o formato ASCII.
Os valores TRUE ou FALSE são determinados de acordo com uma tabela existente num arquivo
chamado fobjvbs.inc , o qual deve ser incluído no código da página que contém o código ASP de
leitura do arquivo texto.(veja exemplo mais abaixo)
Abaixo, uma tabela dos vários comandos desse componente:
Retorna TRUE caso o ponteiro tenha chegado ao final da
AtEndOfLine
linha. Usado apenas em arquivos abertos para leitura.
Retorna TRUE caso o ponteiro tenha chegado ao final do
AtEndOfStream
arquivo. Usado apenas em arquivos abertos para leitura.
Retorna o número da coluna que o ponteiro se encontra. A
Column
primeira coluna tem numeração 1.
Retorna o número da linha que o ponteiro se encontra. A
Line
primeira linha tem numeração 1.
Close Fecha um arquivo aberto.
Read Lê um determinado número de caracteres do arquivo.
Lê todo o arquivo. Quando o arquivo for muito grande, usar
ReadAll
outros métodos de leitura, como a leitura de linha por linha.
Lê uma linha inteira, ou seja, lê os caracteres que estão entre
ReadLine
a posição do ponteiro e o final da linha.
Skip pula um determinado numero de caracteres.
SkipLine pula uma linha inteira.
Write grava uma determinada string para o arquivo.
grava uma determinada string para o arquivo e posiciona o
WriteLine
ponteiro no início da linha seguinte.
WriteBlankLines grava uma determinada quantia de linhas brancas ao arquivo.
Veja os exemplos a seguir:
<HTML><HEAD><TITLE>Componente File Access</TITLE></HEAD>
<BODY>
<!--#include file="fobjvbs.inc"-->
<%
Set objeto= CreateObject("Scripting.FileSystemObjects")
'a linha acima criou uma instância do componente FileAccess
Set gv = objeto.OpenTextFile("c:\test.txt", ForWriting, True, False)
'a linha acima abre o arquivo C:\test.txt para gravação. Caso ele não exista., é criado um.
(este código tem exatamente o mesmo efeito do método CREATETEXTFILE.
gv.Writeline("Esta linha foi inserida com o uso do componente FileAccess.")

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 9 de 93

gv.Close
'a linha acima fecha o arquivo aberto para gravação
objeto=nothing
'a linha acima libera a variável objeto, dessa forma, ela não fica armazenando valores que
não serão mais usados após o fechamento do arquivo.
%>
<p>Pronto. Foi gravada a linha acima</p>
</BODY></HTML>
Componente Browser Capabilities
O componente Browser Capabilities tem como objetivo ser usado para determinar quais são as
propriedades que cada Browser (navegador) que está acessando o seu site tem. Desde o nome e
versão até a detecção de suporte a JavaScript, Applet Java, Cookies, etc. Abaixo, uma lista
contendo as propriedades que podem ser determinadas a partir do componente Browser
Capabilites.
ActiveXControls Especifica quando o browser suporta controles ActiveX
Especifica quando o browser tem capacidade de tocar som de fundo
backgroundsounds
(back ground sound)
beta Especifica quando o brower é versão beta.
browser Especifica o nome do browser
cookies Especifica se o browser aceita cookies
frames Especifica se o browser suporta frames
Especifica se o browser suporta Applets Java (ou, em alguns casos,
javaapplets
se o suporte a Applets Java está ativo)
Especifica se o browser suporta JavaScript (ou, em alguns casos, se
javascript
o suporte a Java Script está ativo)
Especifica o número mais significativo da Versão (na versão 4.01,
majorver
por exemplo, é retornado o número 4)
Especifica os números menos significativos da Versão (no exemplo
minorver
acima, retorna o número 01)
platform Especifica em qual sistema operacional o browser está instalado
tables Especifica se o browser suporta tabelas
Especifica quando o browser suporta vbscript (processamento local
vbscript de vbscript - não há nada a ver com o vbscript usado na
programação ASP, o qual é processado no servidor)
version Retorna o número da versão do browser (exemplo: 4.01)
Especifica se o browser roda num computador com sistema
win16 operacional 16 bits (win3.x). Válido somente para Internet
Explorer.
Caso alguma dessas especificações não seja definida pelo browser, a string "UNKNOWN" é
retornada.
sintax:
Set bc = Server.CreateObject("MSWC.BrowserType")
... = bc.propriedade
<html><head>
<TITLE>Componente browser Capabilities</TITLE>
</head><body bgcolor="#FFFFFF">
<% Set bc = Server.CreateObject("MSWC.BrowserType") %>
Browser: <%=bc.browser %><p>
Versão: <%=bc.version%><p>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 10 de 93

<% if (bc.frames = TRUE) then %>


Este browser aceita frames<p><p>
<% else %>
É melhor você trocar de Browser. Este não suporta frames...
<% end if %>
<% if (bc.tables = TRUE) then %>
Legal. Este browser aceita tabelas...<p>
<% else %>
É melhor você trocar de Browser. Este não suporta nem tabelas...é bem velhinho...<p>
<% end if %>
<% if (bc.BackgroundSounds = TRUE)then %>
Este browser permite que haja fundo musical nas páginas<p>
<% else %>
Ou este browser é bem antiguinho, ou você realmente não gosta de muito barulho.<p>
<% end if %>

<% if (bc.vbscript = TRUE) then %>


Este Browser aceita processamento local de VBScript<p>
<% else %>
Este Browser não permite o processamento local de VBScript<p>
<% end if %>

<% if (bc.javascript = TRUE) then %>


Este Browser aceita processamento local de JavaScript<p>
<% else %>
Este Browser não permite o processamento local de JavaScript<p>
<%
end if
set bc=nothing
%>
</body></html>
clique aqui para rodar a rotina acima
Application/Session Obj.
O objeto Application tem como objetivo armazenar e compartilhar valores, estados e propriedades
de um grupo. No caso, valores comuns a todos os visitantes do site, como número total de
visitantes no site, quantas pessoas estão visitando o site no momento, etc.

O objeto session tem como objetivo armazenar e compartilhar valores, estados e propriedades de
cada visitante, individualmente. São bons exemplos o uso em lojas virtuais, onde a cesta de
compras pode ser armazenada dentro de uma session.

O objeto Application é ativado quando for feita a primeira visita ao site, e termina quando o servidor
for desligado (é permitido gravar todos esses valores em banco de dados, assim não há perda dos
valores). Todo o script e códigos de armazenamento somente podem ser escritos em um arquivo
chamado global.asa, que deve permanecer na pasta raiz do site
.
O objeto session é criado para cada visitante, cada vez que um visitante entra no site, e é
destruído toda vez que este visitante sai do site. Ao entrar no site, cada visitante recebe um ID
(número de identificação), o qual é usado para identificar o usuário e para armazenar os valores,
estados e propriedades de cada visitante, individualmente.
O arquivo global.asa tem o seguinte formato:

<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>


Sub Application_OnStart
End sub
Sub Application_OnEnd

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 11 de 93

End sub
Sub Session_OnStart
End sub
Sub Session_OnEnd
End sub
</SCRIPT>

Nos eventos Application_OnStart e Application_OnEnd estão armazenados os valores comuns


a todos os visitantes. Nos eventos Session_OnStart e Session_OnEnd estão armazenados os
códigos, scripts e valores usados nas sessions (valores individuais para cada visitante).
Métodos dos Objetos Application e Session:

Application.Lock -> é usado para bloquear o acesso de outras páginas ao evento


Application_OnStart ou Application_OnEnd, com excessão da página que requisitou o bloqueio,
permitindo assim que somente esta página possa fazer alterações no evento.

Application_Unlock -> Desbloqueia o acesso de outras páginas.


Esses métodos são usados para que duas páginas não tentem alterar as mesmas propriedades ou
valores ao mesmo tempo. Pois isso acarretaria numa perda de consistência dos dados
armazenados.

Abaixo, um exemplo de como saber o número de visitantes totais do site e o número de visitantes
no site no presente momento.
<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>
Sub Application_OnStart
Application("Totalvisitas") = 0
Application("datainicial") = now
Application("Visitasatuais") = 0
End sub
Sub Application_OnEnd
End sub
Sub Session_OnStart
Application.Lock
Application("Totalvisitas") = Application("Totalvisitas") + 1
Application("Visitasatuais") = Application("Visitasatuais") + 1
Application.Unlock
End sub
Sub Session_OnEnd
Application.Lock
Application("Visitasatuais") = Application("Visitasatuais") -1
Application.Unlock
End sub
</SCRIPT>
abaixo, código para exibir esses valores.
<HTML><header><title>Application & Session</title></header>
<body>
<%
response.write "Visitas totais desde" & application("datainicial") & ":" &
application("Totalvisitas")
response.write "Visitantes no site no momento:" & application("Visitasatuais")
%>
</body>
</html>
Componente Database
O componente Database Access é um componente usado para acessar bancos de dados de
acesso aleatório, tais como Access, SQLServer, DBF, Oracle, ...

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 12 de 93

O componente Database Access permite a consulta, inserção, alteração e exclusão de dados


nos bancos de dados.Tais operações são, geralmente, feitas através de comandos SQL
(Structured Query Language), a qual será exemplificada mais abaixo.
Este tutorial não contém todos os comandos e possibilidades de uso do componente
Database Access, uma vez que este é muito grande e complexo, mas os comandos e
métodos mais utilizados estão citados neste documento.
sintaxe:
conexão com o componente: Set Conn = Server.CreateObject("ADODB.Connection")
abertura de um banco de dados já existente: Conn.Open "nome da ligação ODBC ou path do
BD", "UserID", "Senha"
execução de comandos SQL: Set rsQuery = Conn.Execute("string SQL")
um modo alternativo de se abrir um banco de dados para gravação:
Set RS = Server.CreateObject("ADODB.RecordSet")
RS.Open "tabela", Conn , adOpenKeyset, adLockOptimistic
Para o funcionamento correto do componente ASP, o arquivo adovbs.inc deve ser incluído no
código da página que contém o código de manipulação do banco de dados.
Abaixo, uma tabela com alguns dos comandos mais usados desse componente:
Retorna TRUE caso o ponteiro tenha chegado ao final do
EOF
arquivo.(depois do último registro)
Retorna TRUE caso o ponteiro esteja posicionado no início do
BOF
arquivo.(antes do primeiro registro)
MoveFirst Posiciona o ponteiro para o início do banco de dados.
MoveLast Posiciona o ponteiro no final do banco de dados
MoveNext Move o ponteiro 1 registro adiante no banco de dados.
MovePrevious Move o ponteiro para o registro anterior no banco de dados.
Adiciona um novo registro ao banco de dados. É usado
AddNew quando, ao invés de usar SQL, abre-se o banco de dados no
modo RecordSet.
Salva as alterações feitas no banco de dados, no modo
Update
RecordSet.
Veja os exemplos a seguir:
<HTML><HEAD><TITLE>Adicionando um novo registro ao banco de dados
cadastro</TITLE></HEAD>
<BODY>
<!--#include file="adovbs.inc"-->
<%
'a variavel abaixo - Connstring - guarda o path físico do banco de dados no servidor. poderia
armazenar, no lugar do path, o nome da conexão ODBC, caso esta tenha sido criada (como
será visto no próximo exemplo)
ConnString="DBQ=e:\aspbrasil\teste.mdb;Driver={Microsoft Access Driver (*.mdb)}"
Set Conn = Server.CreateObject("ADODB.Connection")
Set RS = Server.CreateObject("ADODB.RecordSet")
Conn.Open ConnString,"",""
RS.Open "cadastro", Conn , adOpenKeyset, adLockOptimistic
RS.Addnew
RS("nome") = "João"
'a linha acima atribui o valor João ao campo nome, nesse novo registro.
RS("email") = "joao@aspbrasil.com.br"
'a linha acima atribui o valor joao@aspbrasil.com.br ao campo email do banco de dados.
RS.update

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 13 de 93

'a linha acima confirma a inclusão dos dados. Caso este comando não seja usado, o registro
não é inserido.
RS.Close
Set Conn = nothing
Set RS = nothing
%>
<p>Pronto. Foi gravado o registro acima.</p>
</BODY></HTML>
<HTML><HEAD><TITLE>Adicionando um novo registro ao banco de dados cadastro usando
ligação ODBC</TITLE></HEAD>
<BODY>
<!--#include file="adovbs.inc"-->
<%
'a variavel abaixo - Connstring - guarda o nome da conexão ODBC (há a necessidade de a
ligação ODBC já estar criada).
ConnString="odbcteste"
Set Conn = Server.CreateObject("ADODB.Connection")
Set RS = Server.CreateObject("ADODB.RecordSet")
Conn.Open ConnString,"",""
RS.Open "cadastro", Conn , adOpenKeyset, adLockOptimistic
RS.Addnew
RS("nome") = "João"
'a linha acima atribui o valor João ao campo nome, nesse novo registro.
RS("email") = "joao@aspbrasil.com.br"
'a linha acima atribui o valor joao@aspbrasil.com.br ao campo email do banco de dados.
RS.update
'a linha acima confirma a inclusão dos dados. Caso este comando não seja usado, o registro
não é inserido.
RS.Close
Set Conn = nothing
Set RS = nothing
%>
<p>Pronto. Foi gravado o registro acima.</p>
</BODY></HTML>
<HTML><HEAD><TITLE>Fazendo uma consulta SQL e mostrando os dados obtidos em uma
tabela</TITLE></HEAD>
<BODY>
<!--#include file="adovbs.inc"-->
<%
'a variavel abaixo - Connstring - guarda o nome da conexão ODBC (há a necessidade de a
ligação ODBC já estar criada).
ConnString="odbcteste"
'a variável abaixo guarda a string SQL, usada para fazer a consulta no banco de dados. No
caso, pede-se para gerar uma consulta onde apenas os registros onde o campo NOME é
igual ao valor JOÃO.
SQLstring = "select * from cadastro where nome = 'joão' "
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open ConnString,"",""
Set rsQuery = Conn.Execute(SQLstring)
'a linha acima gerou uma consulta chamada rsQuery. todos os registros que satisfazem a
SQLstring estão armazenados nesta variável.
%>
<table>
<tr><td>Nome</td><td>email</td></tr>
<%
While not rsQuery.EOF

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 14 de 93

%>
<tr><td><%=rsQuery("nome").value%></td><td><%=rsQuery("email").value%></td></tr>
<%
rsQuery.Movenext
Wend
%>
</table>
<%
rsQuery.Close
set Conn = nothing
Set rsQuery = nothing
%>
</BODY></HTML>
<HTML><HEAD><TITLE>Fazendo uma alteração via SQL</TITLE></HEAD>
<BODY>
<!--#include file="adovbs.inc"-->
<%
'a variavel abaixo - Connstring - guarda o nome da conexão ODBC (há a necessidade de a
ligação ODBC já estar criada).
ConnString="odbcteste"
'a variável abaixo guarda a string SQL, usada para fazer a atualização no banco de dados.
No caso, pede-se para mudar o nome e o email do registro de código 5.
SQLstring = "update cadastro set nome = 'maria' and email='maria@aspbrasil.com.br' "
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open ConnString,"",""
Set rsQuery = Conn.Execute(SQLstring)
rsQuery.Close
Set Conn = nothing
Set rsQuery = nothing
%>
<p>Arquivo alterado.</p>
</BODY></HTML>
<HTML><HEAD><TITLE>Fazendo uma exclusão de registro via SQL</TITLE></HEAD>
<BODY>
<!--#include file="adovbs.inc"-->
<%
'a variavel abaixo - Connstring - guarda o nome da conexão ODBC (há a necessidade de a
ligação ODBC já estar criada).
ConnString="odbcteste"
'a variável abaixo guarda a string SQL, usada para fazer a exclusão do registro no banco de
dados. No caso, pede-se para excluir o(s) registro(s) onde o código é 5. Por se tratar de um
número e não de uma string, o valor do código, no caso 5, não fica entre aspas.
SQLstring = "delete * from cadastro where codigo = 5 "
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open ConnString,"",""
Set rsQuery = Conn.Execute(SQLstring)
Set rsQuery = nothing
Set Conn = nothing
%>
<p>Registro Excluído</p>
</BODY></HTML>
Server Variables
ServerVariables é um conjunto de variáveis de sistema, que podem indicar desde o IP remoto,
protocolo, HOST do servidor de acesso do usuário, etc.
sintaxe:
valor = Request.ServerVariables("variável")

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 15 de 93

Abaixo, uma tabela com as principais variáveis desse conjunto.


CONTENT_LENGTH Retorna o tipo de conteúdo que foi enviado ao servidor.
QUERY_STRING String que sucede o ? no endereço URL.
REMOTE_ADDR IP do usuário
Nome do servidor correspondente ao REMOTE_ADDR (nome
REMOTE_HOST
do provedor de acesso do usuário)
Método usado para transmissão das variáveis de uma página
REQUEST_METHOD
para outra (GET ou POST)
Nome do servidor de hospedagem, como usado no URL
SERVER_NAME
(pode ser o IP ou DNS)
URL endereço URL requisitado (sem a query_string)
Veja os exemplos a seguir:
<HTML><HEAD><TITLE>Server Variables </TITLE></HEAD>
<BODY><p>o IP usado pela sua conexão é: <%=request.servervariables("REMOTE_ADDR")
%></p></BODY>
</HTML>
clique aqui para rodar a rotina acima
Cookies
Cookies são pequenos arquivos no formato txt, gravados nos computadores dos usuários,
contendo informações que podem ser recuperadas posteriormente.
sintaxe:
gravação de informações no cookie: response.cookies("nomedocookie")("nomedoparametro")
= "valordoparâmetro"
recuperação de informações do cookie: variável = request.cookies("nomedocookie")
("nomedoparametro")
determinação da data de expiração do cookie: Response.Cookies("nomedocookies").Expires =
data no formato mm/dd/aa
obs: caso não seja determinada uma data de expiração, o cookie será apagado assim que o
browser for fechado.
Veja os exemplos a seguir:
<%
response.cookies("aspbrasilteste")("data") = now
response.cookies("aspbrasilteste")("nome") = "João"
'as linhas acima criaram o cookie aspbrasil e 2 parâmetros, data e nome.
response.cookies("aspbrasilteste").expires = "6/25/99"
'a linha acima determina uma data de expiração do cookie
%>
<HTML><HEAD> <TITLE>Criando um cookie</TITLE>
</HEAD>
<BODY>
<%
response.write "O cookies aspbrasilteste foi criado em: " & request("aspbrasilteste")("data")
response.write "Quem criou foi: " & request("aspbrasilteste")("nome")
%>
</BODY></HTML>

Objetos Application e Session

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 16 de 93

O objeto Application foi criado para armazenar propriedades (valores) ligados a um conjunto de
usuários. No caso, os visitantes do site, de um modo geral. Como exemplo, podemos citar o
número total de visitantes no site a partir de uma determinada data, ou o número de visitantes
online no site.
O objeto Session foi criado para armazenar propriedades (valores) ligados a cada visitante,
individualmente. Como exemplo, podemos citar o carrinho de compras de um site de comércio
online.
Uma Session é criada quando o visitante entra no site (cada visitante tem uma session e cada
session recebe um ID), e é destruída quando o visitante sai do site (seja por logoff explícito ou por
TimeOut). Já uma Application é iniciada ao haver o primeiro pedido de acesso ao objeto
Application, e é encerrado quando o servidor for desligado.
Todo o código que se deseja executar ao criar ou destruir uma session, bem como uma Application
devem estar contidos no arquivo global.asa, um arquivo texto no formato abaixo demonstrado, que
deve ser colocado no diretório raiz do site.
As variáveis do objeto Application e do objeto Session são armazenadas no servidor, mas é
necessário que o browser aceite cookies, pois um cookie com o ID da sessão é criado no
computador do visitante, para identificá-lo.
Veja o exemplo abaixo:
Listagem do arquivo global.asa

<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>


Sub Application_OnStart
Application("totaldeusuarios") = 0
Application("datainicial") = now
Application("usuariosonline") = 0
End Sub
Sub Application_OnEnd
End Sub
Sub Session_OnStart
Session.TimeOut = 20
Application.Lock
Application("totaldeusuarios") = Application("totaldeusuarios") + 1
Application("usuariosonline") = Application("usuariosonline") + 1
Application.Unlock
End Sub
Sub Session_OnEnd
Application.Lock
Application("usuariosonline") = Application("usuariosonline") - 1
Application.Unlock
End Sub
</SCRIPT>

Abaixo, o código de uma página que armazena um valor numa variável de sessão e mostra o total
de usuários conectados e o total de visitantes no site.

<html><head><title>Application e Session</title></head>
<% Session("variavelqualquer") = "Este valor foi inserido na variável de sessão de nome
variavelqualquer" %>
<body>
<p>Número da Sessão: <%=Session.SessionID%></p>
<p>Existem no momento <%=Application("usuariosonline")%> usuários conectados.</p>
<p>Total de visitantes no site desde <%=Application("datainicial")%> : <
%=Application("totaldeusuarios")%></p>
<p>Abaixo, a string que foi inserida na variavel variavelqualquer</p>
<p><%=Session("variavelqualquer")%></p>
<% Session.Abandon %>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 17 de 93

</body></html>
clique aqui ara rodar a rotina acima

Os comandos Lock e Unlock servem para garantir que somente um visitante estará alterando as
variáveis por vez. O comando Lock bloqueia a acesso de outros visitantes às variáveis, e o Unlock
desbloqueia.
O comando Session.SessionID retorna o valor do ID da sessão.

O comando Session.TimeOut determina qual o tempo máximo, em minutos, de inatividade do


visitante até que a sessão possa ser considerada abandonada
.
O comando Session.Abandon termina a sessão iniciada explicitamente (não é necessário esperar
o vencimento do TimeOut para considerar a sessão abandonada).

A procedure Application_OnStart contém a rotina que será rodada quando o objeto Application for
iniciado.

A procedure Application_OnEnd contém a rotina que será executada quando o objeto Application
for terminado (qdo. o servidor for desligado).
A procedure Session_OnStart contém o código que será rodado quando uma sessão for iniciada.
A procedure Session_OnEnd contém o código que será rodado quando uma sessão for terminada
(por timeout ou logoff explícito).

Procedures
Algumas vezes, em programação, uma mesma sequência de códigos precisa ser usado
constantemente. Ao invés de copiá-los toda vez que for preciso, pode-se usar as Procedures.
Procedures são caixas pretas, onde vc entra com alguns dados, a caixa preta processa, e no caso
das Functions, retorna outros valores, de acordo com um algorítimo. Existem dois tipos de
Procedures, as Subs e as Functions. Observe os exemplos abaixo:
<html><body>
<%
Function soma(valor1,valor2)
If valor1 = "" then valor1 = 0
If valor2 = "" then valor2 = 0
soma = valor1 + valor2
End Function
'acima, a função denominada soma foi apresentada
'abaixo, uma chamada à função foi feita. Então a função executa a rotina e retorna um
determinado valor, no caso 5.

response.write soma(2,3)
%></body></html>

Já uma Sub simplesmente executa uma ação, não retornando valor algum.
<html><body>
<%
Sub visualizar_nome(nome)
response.write "O nome do site é: " & nome
End Sub
'acima, a procedure do tipo Sub foi denominada visualizar_nome

response.write "Qual é o site sobre ASP que oferece Tutoriais, Newsgroups e Links a seus
visitantes?"
Call visualizar_nome("ASPBRASIL")

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 18 de 93

response.write "<div><a href=www.aspbrasil.com.br>Home</a></div>"


'acima, o comando Call faz a chamada à Sub visualizar_nome. Como pode-se perceber, uma
Sub não retorna nenhum valor, e sim executa uma ação.

%>
</body></html>

If...Then...Else ; Select Case


Existem 2 comandos capazes de identificar o conteúdo de uma determinada variável, e de
acordo com esse valor, executar uma determinada rotina:
If...Then...Else
Select Case
If...Then...Else
O comando If...Then...Else possibilita verificar se uma determinada variável está ou não de acordo
com um critério de seleção. Observe o exemplo abaixo:
<html><body>
<%
variavel_qualquer = hour(now)
If variavel_qualquer < 19 then
response.write "Bom Dia"
Else
response.write "Boa Noite"
End if
'o comando IF...then...Else comparou o valor da variavel variavel_qualquer com um
determinado valor estipulado (no caso, 19). Se o valor for menor que 19, então escreva na
tela "Bom Dia". Caso contrário (Else), "Boa Noite"
%></body></html>

Select Case
O comando Select Case permite um maior controle sobre os valores de uma determinada variavel.
Observe o Exemplo Abaixo:
<html><body>
<%
variavel_qualquer = hour(now)
Select Case variavel_qualquer
case 0,1,2,3,4,5,6,7,8,9,10,11,12
response.write "Bom Dia"
case 13,14,15,16,17,18,19
response.write "Boa Tarde"
case 20,21,22,23,24
response.write "Boa Noite"
Case else
response.write "Este relógio está maluco"
End Select
%></body></html>

observe que o comando Select Case deve ser fechado com o comando End Select.

Rotinas de Loop

Loops são rotinas que devem ser repetidas até que uma determinada condição seja satisfeita.
Existem 3 comandos que permitem tal situação:

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 19 de 93

Do...Loop
For...Next
While...Wend

Abaixo seguem as características e exemplos de cada comando.


Do...Loop
O comando Do...Loop executa uma determinada rotina até que a condição se torne verdadeira.
Observe o exemplo abaixo:
<html><body>
<%
x=0
Do Until x=10
x=x+1
Loop
response.write x
%></body></html>
para interromper o Loop, usa-se o comando Exit Do

For...Next
O comando For...Next executa uma determinada rotina até que o contador (uma variável) atinja o
valor determinado. Observe o exemplo:
<html><body>
<%
For i=1 to 50
response.write i
next
%></body></html>

observe que não é necessário nenhuma rotina de incrementação de valores em i. A cada


ciclo, o valor de i é acrescido de uma unidade, automaticamente.
para interromper o Loop, usa-se o comando Exit For

While...Wend
O comando While...Wend executa uma determinada rotina até que a condição imposta seja
alcançada. Observe o exemplo dado:
<html><body>
<%
q = "SELECT * FROM cadastro where cidade = 'São Paulo'"
connstring = "DBQ=c:\teste.mdb;Driver={Microsoft Access Driver (*.mdb)}"
Set Conexao = Server.CreateObject("ADODB.Connection")
Conexao.Open connstring, "",""
Set tabela = Conexao.Execute (q)
While not tabela.EOF
response.write tabela("nome").value
wend
%></body></html>

Tipos de Dados
O VBScript contém apenas um tipo de variável, denominado Variant. O tipo variant pode
armazenar qualquer tipo de dado, e de acordo com o tipo de dados que é armazenado, é possível
classifica-lo de acordo com os subtipos de dados, abaixo relacionados:

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 20 de 93

Subtipo Descrição

Empty Variável que contém 0 para valores numéricos e "" (string vazia) para
strings.

Null Variável que não contém dado algum.

Boolean Contém True ou False

Byte Números inteiros entre 0 e 255

Integer Números inteiros no intervalo de -32,768 a 32,767.

Long Números inteiros no intervalo de -2,147,483,648 a 2,147,483,647.

Single Números com ponto flutuante de precisão simples na faixa de


-3.402823E38 a -1.401298E-45 para números negativos e 1.401298E-45
a 3.402823E38 para números positivos.

Double Números com ponto flutuante de dupla precisão na faixa de


-1.79769313486232E308 a -4.94065645841247E-324 para números
negativos e 4.94065645841247E-324 a 1.79769313486232E308 para
números positivos.

Date Dados no formato de Data (data e tempo) na faixa de 1 de janeiro de 100


(Time) a 31 de dezembro de 999. (January 1, 100 a December 31, 9999).

String Contém dados no formato de string, que podem ter até aproximadamente
2 bilhões de caracteres de tamanho.

PS: é possível a conversão de dados de um tipo para outro, mas para isso, os dados devem ser
compatíveis com o subtipo desejado, ou seja, a String "23/5/99" pode ser convertida para o subtipo
Date, e vice-versa. Mas a String "ASPBRASIL" não pode.
É importante a conversão de tipos de dados uma vez que o modo como os dados serão
manipulados dependem do seu subtipo.

Convertendo Dados

Verificando e Convertendo Tipos de Dados


A linguagem VBScript contém algumas funções de verificação e conversão de tipos de dados
importantes para a melhor manipulação dos dados.
As funções de verificação são importantes na hora de detectar se os dados contidos numa variável
são compatíveis com o subtipo para o qual se deseja converter estes dados.
As funções de conversão fazem a conversão de dados de um subtipo para outro, mas para isso, é
necessário que esses dados sejam compatíveis com o subtipo que se deseja obter.
Funções de Verificação
IsArray - IsDate - IsEmpty - IsNull - IsNumeric

Funções de Conversão
CBool - CByte - CDate - CDbl - CInt - CLng - CStr - CSng
Convertendo Dados
Verificando e Convertendo Tipos de Dados
A linguagem VBScript contém algumas funções de verificação e conversão de tipos de dados
importantes para a melhor manipulação dos dados.

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 21 de 93

As funções de verificação são importantes na hora de detectar se os dados contidos numa variável
são compatíveis com o subtipo para o qual se deseja converter estes dados.
As funções de conversão fazem a conversão de dados de um subtipo para outro, mas para isso, é
necessário que esses dados sejam compatíveis com o subtipo que se deseja obter.
Funções de Verificação
IsArray - IsDate - IsEmpty - IsNull - IsNumeric

Funções de Conversão
CBool - CByte - CDate - CDbl - CInt - CLng - CStr - CSng

IsArray - retorna True caso a variável seja um array, caso contrário, retorna False.
sintaxe: IsArray(nomedavariavel)
<%
Dim aspbrasil
Dim Arraybrasil(5)
response.write IsArray(aspbrasil) 'retorna false
response.write IsArray(Arraybrasil) 'retorna true
%>
IsDate - retorna True caso o valor da variável possa ser convertido em data, caso contrário, retorna
False.
sintaxe: IsDate(nomedavariavel)
<%
aspbrasil = "23/5/99"
aspbrasil2 = "ASPBRASIL"
response.write IsDate(aspbrasil) 'retorna true
response.write IsDate(aspbrasil2) 'retorna false
%>
IsEmpty - retorna True caso a variável contenha o valor 0 ou "", caso contrário, retorna False.
sintaxe: IsEmpty(nomedavariavel)
<%
aspbrasil = ""
aspbrasil2 = 0
aspbrasil3 = "ASPBRASIL"
response.write IsEmpty(aspbrasil) 'retorna true
response.write IsEmpty(aspbrasil2) 'retorna true
response.write IsEmpty(aspbrasil3) 'retorna false
%>
IsNull - retorna True caso a variável não contenha dados válidos.
sintaxe: IsNull(nomedavariavel)
<%
aspbrasil = "23/5/99"
response.write IsNull(aspbrasil) 'retorna false
%>
IsNumeric - retorna True caso o valor da variável possa ser convertido para algum tipo de dados
numéricos.
* A conversão de tipo de dados numéricos entre si, ou seja, de um número Double para o formato
Sng pode acarretar a perda de dados, ou mesmo, podem ser imcompatíveis, uma vez que existem
faixas de atuação para cada tipo de dado.
sintaxe: IsNumeric(nomedavariavel)
<%
aspbrasil = "23"
aspbrasil2 = 56
response.write IsNumeric(aspbrasil) 'retorna true

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 22 de 93

response.write IsNumeric(aspbrasil2) 'retorna true


%>
CBool - retorna True ou False (0 ou 1), de acordo com a expressão analisada ou com o valor da
variável.
sintaxe: CBool(nomedavariavel ou expressão)

<%
aspbrasil = 5
aspbrasil2 = 5
aspbrasil3 = 0

response.write CBool(aspbrasil = aspbrasil2) 'retorna true


response.write CBoll(aspbrasil3) 'retorna false
%>
CByte - converte a expressão dada em um dado do subtipo Byte.
sintaxe: CByte(nomedavariavel ou expressão)
<%
aspbrasil = "23"
aspbrasil2 = 34.67
response.write IsArray(aspbrasil) 'retorna 23
response.write IsArray(aspbrasil2) 'retorna 35, pois há um arredondamento
%>
CDate - converte a expressão dada em um dado do subtipo Date.
sintaxe: CDate(nomedavariavel)
<%
aspbrasil = "23/5/99"
response.write CDate(aspbrasil) 'convertendo strings de data e tempo para o subtipo Date, é
possível fazer operações matemáticas com essas datas, somando dias, meses, segundos, anos...
%>
CDbl - converte a expressão dada em um dado do subtipo Double.
sintaxe: CDbl(nomedavariavel ou expressão)
<%
aspbrasil2 = 34.6767786543E56
response.write CDbl(aspbrasil2)
%>
CInt - converte a expressão dada em um dado do subtipo Integer. A diferença para o subtipo Byte é
a faixa de abrangência.
sintaxe: CInt(nomedavariavel ou expressão)
<%
aspbrasil = "23"
aspbrasil2 = 34.67
response.write CIntaspbrasil) 'retorna 23
response.write CInt(aspbrasil2) 'retorna 35, pois há um arredondamento
%>
CLng - converte a expressão dada em um dado do subtipo Long. A diferença para o subtipo byte é
a faixa de abrangência.
sintaxe: CByte(nomedavariavel ou expressão)
<%
aspbrasil = "23"
aspbrasil2 = 34.6
7response.write CLng(aspbrasil) 'retorna 23
response.write CLng(aspbrasil2) 'retorna 35, pois há um arredondamento
%>
CSng - converte a expressão dada em um dado do subtipo Single.
sintaxe: CInt(nomedavariavel ou expressão)
<%

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 23 de 93

aspbrasil2 = 88734.679999
response.write CInt(aspbrasil2)
%>
CStr- converte a expressão dada em um dado do subtipo String. Qualquer outro tipo de dado, dos
listados acima, pode ser convertido em String.
sintaxe: CStr(nomedavariavel ou expressão)
<%
aspbrasil2 = 34.67
response.write CStr(aspbrasil2) 'retorna "23"
%>

Manipulando Números
Manipulando Datas

O VBScript contém várias funções utilizadas para a manipulação de dados numéricos. Abaixo uma
lista das principais funções. Os operadores básicos (+,-,*,/,^) estão descritos no tutorial sobre
Operadores Básicos do VBScript.
Abs - Atn - Cos - Exp - Fix - Int - Log - Sin - Sqr - Tan

Abs - retorna o módulo do valor de entrada


sintaxe: Abs(número)
<%
aspbrasil = -78
response.write Abs(aspbrasil)
%>
Atn - retorna o valor do arcotangente do valor entrado (resposta em radianos)
sintaxe: Atn(número)
<%
aspbrasil = 1
response.write Atn(aspbrasil)
%>
Cos - retorna o valor do cosseno do angulo entrado (entrar angulo em radianos)
sintaxe: Cos(angulo)
<%
aspbrasil = 3,1416
response.write Cos(aspbrasil)
%>
Exp - retorna o valor de e (euler) elevedo ao valor de entrada (e^x)
sintaxe: Exp(numero)
<%
aspbrasil = 3
response.write Exp(aspbrasil)
%>
Fix - retorna a parte inteira de um número.
sintaxe: Fix(número)
<%
aspbrasil = 78.778
response.write Fix(aspbrasil)
%>
Int - retorna a parte inteira de um número. Caso o número seja negativo, é retornado o valor
imediatamente menor.
sintaxe: Int(número)
<%
aspbrasil = -78,389
response.write Int(aspbrasil)

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 24 de 93

%>
Log - retorna o valor do Log do número de entrada na base e.
sintaxe: Log(número)
<%
aspbrasil = 4
response.write Log(aspbrasil)
%>
Sin - retorna o valor do seno de um angulo entrado em radianos.
sintaxe: Sin(angulo)
<%
aspbrasil = 3,1416
response.write Sin(aspbrasil)
%>
Sqr - retorna o valor da raiz quadrada do número de entrada.(valor deve ser maior ou igual a zero)
sintaxe: Sqr(numero)
<%
aspbrasil = 4
response.write Sqr(aspbrasil)i
%>
Tan - retorna o valor da tangente do angulo pedido (entrar angulo em radianos)
sintaxe: Tan(angulo)
<%
aspbrasil = 2
response.write Tan(aspbrasil)
%>

Manipulando Datas
Manipulando Datas
O VBScript possibilita a obtenção e manipulação de dados no formato Data e Tempo facilmente.
Abaixo, uma lista das principais funções relacionadas a esse tópico.
CDate - Date - DateSerial - Day - Hour - IsDate - Minute - Month - Now - Second - Time -
TimeSerial - TimeValue - Weekday - Year

CDate - converte a expressão dada em um dado do subtipo Date.


sintaxe: CDate(nomedavariavel)
<%
aspbrasil = "23/5/99"
response.write CDate(aspbrasil) 'convertendo strings de data e tempo para o subtipo Date, é
possível fazer operações matemáticas com essas datas, somando dias, meses, segundos, anos...
%>
Date - retorna a data do sistema (a data que consta no relógio do servidor).
sintaxe: Date
<%
response.write Date
%>
DateSerial - retorna um valor do subtipo data para um determinado valor de ano, mes e dia, ou
seja, entrando esses 3 valores respectivamente, a função DateSerial retorna a data respectiva no
formato Date.
sintaxe: DateSerial(year, month, day)
<%
response.write DateSerial(99,12,23)
%>
Day - retorna um número entre 1 e 31, representando o dia de uma determinada data.
sintaxe: Day(data)
<%

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 25 de 93

response.write Day(now)
%>
Hour - retorna um número entre 0 e 23 representando a hora de uma determinada expressão de
tempo.
sintaxe: Date
<%
response.write Date
%>
IsDate - retorna True caso o valor da variável possa ser convertido em data, caso contrário, retorna
False.
sintaxe: IsDate(nomedavariavel)
<%
aspbrasil = "23/5/99"
aspbrasil2 = "ASPBRASIL"
response.write IsDate(aspbrasil) 'retorna true
response.write IsDate(aspbrasil2) 'retorna false
%>
Minute - retorna um número entre 0 e 59 representando os minutos de uma determinada
expressão de tempo.
sintaxe: Minute(tempo)
<%
response.write Minute(now)
%>
Month - retorna um número entre 1 e 12 representando o mês de uma determinada data.
sintaxe: Month(data)
<%
response.write Month(now)
%>
Now - retorna a data e o horário do relógio do servidor.
sintaxe: Now
<%
response.write Now
%>
Second - retorna um número entre 0 e 59 representando os minutos do sistema (o minuto que
consta no relógio do servidor).
sintaxe: Second(tempo)
<%
response.write Second(now)
%>
Time - retorna o horário do relógio do sistema.
sintaxe: Time
<%
response.write Time
%>
TimeSerial - retorna uma expressão do tipo Date contendo o tempo para uma dada hora, minuto e
segundo.
sintaxe: TimeSerial(hora,minuto,segundo)
<%
response.write TimeSerial(22,11,33)
%>
Weekday - retorna o dia da semana de uma determinada data.
sintaxe: Weekday(date)
<%
response.write weekday(now)
%>
Year - retorna o ano de uma determinada data.

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 26 de 93

sintaxe: Year(data)
<%
response.write Year(now)
%>

Manipulando Strings
O VBScript disponibiliza algumas funções utilizadas na manipulação de Strings. Abaixo, as
principais funções, que entre outras coisas, permitem saber o número de caracteres de uma string,
encontrar determinado caracter dentro de uma string, comparar duas strings, etc.
Asc - Chr - CStr - InStr - Lcase - Left - Len - LTrim - Mid - Right - RTrim - Trim - UCase

Asc - Retorna o caracter (pela tabela ANSI) correspondente à primeira letra da string de entrada.
sintaxe: Asc(string)
<%
aspbrasil = "aspbrasil"
response.write Asc(aspbrasil)
%>
Chr -Retorna o caracter correspondente a um determinado codigo (numerico) da tabela ANSI.
sintaxe:Chr(codigo)
<%
response.write Chr(34)
%>
CStr - Converte uma expressão para o formato String. Caso uma variável seja um número, ela
será convertida numa string que represente tal número. Se for uma data, essa data será convertida
numa string que represente tal data.
sintaxe: CStr(expressão)
<%
aspbrasil = 458
response.write CStr(aspbrasil) 'retorna a string, sequencia de caracteres "458", e não o número
458.
%>
InStr - Retorna a posição da primeira ocorrência de uma string dentro da outra. É possível delimitar
a partir de qual caracter será feita tal procura.
sintaxe:InStr(posicaoinicial, string, stringdecomparação)
<%
aspbrasil = "aspbrasil, site sobre ASP em Português."
response.write Instr(4,aspbrasil,"ASP") '4 é a posição a partir da qual a procura será feita.
%>
LCase - Converte todos os caracteres de uma string para minúsculas.
sintaxe: LCase(string)
<%
aspbrasil = "ASPBRASIL"
response.write LCase(aspbrasil) 'deve retornar ASPBRASIL
%>
Left - Retorna um determinado número de caracteres a partir do lado esquerdo da string.
sintaxe: Left(string, numerodecaracteres)
<%
aspbrasil = "aspbrasil, site sobre ASP."
response.write Left(aspbrasil,4) 'deve retornar "aspb"
%>
Len - Retorna o número de caracteres numa string (contando espaços em branco), ou, no caso de
variáveis numéricas, ou no formato Date, retorna a quantidade de bytes necessários para
armazenar aquela expressão.
sintaxe: Asc(string/expressão)
<%

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 27 de 93

aspbrasil = "aspbrasil"
response.write Len(aspbrasil) 'retorna 9
%>
LTrim - Retorna a cópia da string de entrada, mas os espaços no começo do lado esquerdo.
sintaxe: LTrim(string)
<%
aspbrasil = " <--Trim-> "
response.write Asc(aspbrasil) 'retorna "<--Trim-> "
%>
Mid - Função usada para "cortar" uma string. Delimita-se a posição inicial, a string e a quantidade
de caracteres a partir da posição inicial que devem ser "capturados".
sintaxe: Mid(string, posicaoinicial, tamanho)
<%
aspbrasil = "aspbrasil"
response.write Mid(aspbrasil,1,4) 'deve retornar "aspb"
%>
Right - Retorna um determinado número de caracteres a partir do lado direito da string.
sintaxe: Right(string, numerodecaracteres)
<%
aspbrasil = "aspbrasil"
response.write Right(aspbrasil,3) 'deve retornar "sil"
%>
RTrim - Retorna uma cópia da string de entrada, mas sem os espaços no final da string.
sintaxe: RTrim(string)
<%
aspbrasil = "aspbrasil "
response.write Asc(aspbrasil) 'deve retornar "aspbrasil"
%>
Trim - Retorna uma cópia da string de entrada, mas sem os espaços no início e no final da string.
sintaxe: Trim(string)
<%
aspbrasil = " aspbrasil "
response.write Asc(aspbrasil) 'deve retornar "aspbrasil"
%>
UCase - Converte toda a string para MAIÚSCULAS.
sintaxe: UCase(string)
<%
aspbrasil = "aspbrasil"
response.write Asc(aspbrasil) 'deve retornar "ASPBRASIL"
%>

Operadores
Existem alguns caracteres e funções que permitem a ligação de uma ou mais expressões, de
vários modos diferentes. Tais funções e caracteres são chamados Operadores. Abaixo, uma lista
dos mais importantes:
+ - * / \ and & Eqv ^ Imp Mod Not Or Xor

+ (mais)- Usado para somar dois valores numéricos


sintaxe: resultado = expressão1 + expressão2
<%
aspbrasil = 5 + 6
response.write (aspbrasil)
%>
-(menos) -Faz a subtração entre dois números ou indica valor negativo numa expressão numérica.

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 28 de 93

sintaxe:resultado = número1 - número2


<%
response.write (12 - 6)
%>
* (multiplicar) - Usado para multiplicar dois valores numéricos
sintaxe: resultado = expressão1 * expressão2
<%
aspbrasil = 5 * 6
response.write (aspbrasil)
%>
/(dividir) - Usado para dividir um valor por outro.
sintaxe: resultado = numerador/denominador
<%
aspbrasil = 31/7
response.write (aspbrasil)
%>
\ - Usado para dividir um valor por outro, e retornar um valor inteiro.
sintaxe: resultado = numerador/denominador
<%
aspbrasil = 31/7
response.write (aspbrasil)
%>
and - Usado para "validar" um conjunto de duas expressões lógicas. Se, e somente se as duas
expressões tiverem como resulado TRUE, é retornado TRUE. Caso contrário, é retornado FALSE.
sintaxe: resultado = expressão1 and expressão2
<%
aspbrasil = (7>4) and (4<8)
response.write (aspbrasil)
%>
& - Usado para somar duas cadeias de caracteres (strings).
sintaxe: resultado = string1 & string2
<%
aspbrasil = "ASPBRASIL." & "Site sobre ASP na lingua portuguesa."
response.write (aspbrasil)
%>
Eqv - Usado para "validar" um conjunto de expressões lógicas de acordo com a seguinte tabela:
Expressão1 Expressão2 Resultado
true true true
true false false
false true false
false false true
sintaxe: resultado = expressão1 Eqv expressão2
<%
aspbrasil = (6<4) Eqv (8>9)
response.write (aspbrasil)
%>
^ - Usado para "elevar" um número a outro.
sintaxe: resultado = número1^número2
<%
aspbrasil = 6^2
response.write (aspbrasil)
%>
Imp - Usado para "validar" um conjunto de expressões lógicas (Implicação Lógica) de acordo com
a tabela:

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 29 de 93

Expressão1 Expressão2 Resultado


true true true
true false false
true null null
false true true
false false true
false null true
null true true
null false null
null null null

sintaxe: resultado = expressão1 Imp expressão2


<%
aspbrasil = (9<8) Imp (7>4)
response.write (aspbrasil)
%>
Mod - Usado para dividir dois números e retornar apenas o resto.
sintaxe: resultado = número1 Mod número2
<%
aspbrasil = 7 Mod 3
response.write (aspbrasil)
%>
Not - Usado para inverter, ou negar o resultado de uma comparação, como segue na tabela:

Expressão1 Resultado
true false
false true
null null

sintaxe: resultado = Not expressão


<%
aspbrasil = Not (7>6)
response.write (aspbrasil)
%>
Or - Usado para "validar" um conjunto de expressões lógicas de acordo com a tabela:
Expressão1 Expressão2 Resultado
true true true
true false true
true null true
false true true
false false false
false null null
null true true
null false null
null null null

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 30 de 93

sintaxe: resultado = expressão1 Imp expressão2


<%
aspbrasil = (9<8) or (7>4)
response.write (aspbrasil)
%>
Xor - Usado para "validar" um conjunto de expressões lógicas de acordo com a seguinte tabela:
Expressão1 Expressão2 Resultado
true true false
true false true
false true true
false false false
sintaxe: resultado = expressão1 Xor expressão2
<%
aspbrasil = (6<4) Xor (8>9)
response.write (aspbrasil)
%>

Demais Funções do VBScript


Abaixo, algumas importantes funções do VBScript que não se encaixaram no restante dos tópicos.
LBound - Rnd/Randomize - Sgn - UBound - VarType

LBound - Retorna o menor índice de uma determinada dimensão num array.


sintaxe: resultado = LBound(array,dimensão) 'a dimensão é opcional.
<%
dim aspbrasil(8)
aspbrasil(2)="Tigre"
aspbrasil(4)="Onça"
response.write LBound(aspbrasil) 'deve retornar 2
%>
Rnd - Retorna um número randômico entre 0 e 1.
sintaxe:

Randomize
Rnd (numero)
<%
Randomize
aspbrasil = Rnd
response.write aspbrasil
%>
Sgn - Retorna a natureza de um determinado número (maior, menor ou igual a zero), como visto
abaixo:
maior que zero (numero>0) 'retorna 1
igual a zero (numero=0) 'retorna 0
menor que zero (numero<0) 'retorna -1
sintaxe: resultado = Sgn(numero)
<%
aspbrasil = Sgn(-67)
response.write aspbrasil
%>
UBound - Retorna o maior índice de uma determinada dimensão num array.

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 31 de 93

sintaxe: resultado = UBound(array,dimensão) 'a dimensão é opcional.


<%
aspbrasil(2)="Tigre"
aspbrasil(4)="Onça"
response.write UBound(aspbrasil) 'deve retornar 4
%>
Vartype - Retorna um valor, de acordo com a tabela abaixo, indicando o subtipo da variável.
sintaxe: resultado = VarType(variável)
vel)
0 vazia (não inicializada)
1 null (nula)
2 inteiro (int)
3 inteiro longo (lng)
ponto flutuante de precisão simples
4
(Sng)
ponto flutuante de dupla precisão
5
(Dbl)
6 moeda (currency)
7 data (date)
8 String
9 objeto OLE
<%
aspbrasil="aspbrasil"
aspbrasil2 = 34
response.write vartype(aspbrasil) 'deve retornar 8
response.write vartype(aspbrasil2) 'deve retornar 3
%>

One of the most misunderstood features of ADO is the RecordCount property. I've heard from many frustated
users on the topic and quite a few of them have decided that it must just be something that's not supported
with their DB. Well I'm going to try and set the record straight as best I can.

The RecordCount property is supported by both Access and SQL Server. I can't speak for sure on other
platforms, but I've been told it's a pretty widely supported feature and I'd assume most vendors have some
way of doing it.

So why isn't it working for you? Well it's supported only if the recordset supports approximate positioning
(adApproxPosition) or bookmarks (adBookmark). I only mention this so that if you feel like testing for
support you can do so using code like this:
If objRecordset.Supports(adBookmark) Or
objRecordset.Supports(adApproxPosition) Then
' RecordCount will work!
End If
So what the heck does that mean?

Basically it's supported if you use the right kind of cursor. For the most part all client-side cursors support it
as do server-side static and server-side keyset cursors. So the only two that don't are server-side dynamic and
server-side forward only cursors. Unfortunately, most people don't specify the cursor type to use when they
open a recordset and what you usually get when you don't specify one is a server-side, forward only cursor

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 32 de 93

which is one of the ones that doesn't support a record count! So the trick is to specify what type of cursor you
want.

If for some reason you need one of the ones that doesn't support RecordCount, you can get around this by
fully populating the recordset before asking for the RecordCount. This can be accomplished by doing a
MoveLast, but again only if this is supported by the recordset. Otherwise you're basically out of luck unless
you can wait until you've read all the records to get an accurate count.

Oh and one last thing... If you're just trying to get the count and don't care about the records instead or using
ADO, try this SQL syntax instead:

SELECT COUNT(field_name) FROM table_name;

It tends to be easier on the server and you can even use the WHERE clause to limit the results to match
whatever criteria you want. If you want to get really creative, try adding the GROUP BY or other clauses.
With some thought and a little bit of trial and error, you'll soon be counting anything you want in the
database!

<%
' BEGIN CONSTANT DEFINITION

' The following command includes the ADODB VBScript constants


file.
' If you can't find your copy you can download a copy from:
' http://www.asp101.com/samples/download/adovbs.inc
' It may not be the most recent copy so use it at your own risk.

%>
<!-- #INCLUDE FILE="./download/adovbs.inc" -->
<%

' DB Configuration variables


' After this, strictly used as if it were a Const.
Dim DB_CONNSTRING
DB_CONNSTRING = "DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" &
Server.Mappath("./db_scratch.mdb") & ";"

' Now we override the above setting so the sample uses our SQL
server.
' Comment out the following line to use the sample Access DB.
DB_CONNSTRING = Application("SQLConnString") & _
"UID=" & Application("SQLUsername") & ";" & _
"PWD=" & Application("SQLPassword") & ";"

' END CONSTANT DEFINITION


%>

<%
Dim rsCount ' The recordset object

' Create an instance of an ADO Recordset


Set rsCount = Server.CreateObject("ADODB.Recordset")

' Open RS
' I'm actually doing this directly (without a connection object) to keep
' the code short and to the point. I'm opening the RS with a static

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 33 de 93

' cursor, read only, and telling it that "scratch" is a table name and
' not a SQL command. If I don't specify how to open the rs, I'd get the
' default cursor type which doesn't support .RecordCount!
rsCount.Open "scratch", DB_CONNSTRING, adOpenStatic, adLockReadOnly,
adCmdTable

' Show RecordCount


' I dress it up and pop it into the middle of a sentence, but you can
' do whatever you want with it.
Response.Write "This table currently has <B><FONT COLOR=""#FF0000"">"
Response.Write rsCount.RecordCount ' This is the line that does it!
Response.Write "</FONT></B> records in it!<BR>" & vbCrLf

'======================================================================
' BEGIN TABLE DISPLAY
' Now I'm going to display the table if they requested it just so you
' have something to look at! This really doesn't pertain to the topic
' of this sample so I'm going to keep the code short but feel free to
' look it over and if you do please notice the pretty HTML it outputs!
' Ugly HTML output is a pet peeve of mine! ;)
If LCase(Request.QueryString("showtable")) = "true" Then
Dim Field ' Field Looper for display
Dim bColor ' Use for showing alternating colors
bColor = False

' Spacers and intro


Response.Write "<BR>" & vbCrLf & "They are:<BR>" & vbCrLf & "<BR>"
& vbCrLf

' Start the table


Response.Write "<TABLE BORDER=""1"">" & vbCrLf

' Write Titles


Response.Write vbTab & "<TR>" & vbCrLf
For Each Field in rsCount.Fields
Response.Write vbTab & vbTab & "<TD
BGCOLOR=""#CCCCCC""><B>" & Field.Name & "</B></TD>" & vbCrLf
Next 'Field
Response.Write vbTab & "</TR>" & vbCrLf

' Loop through records outputting data


Do While Not rsCount.EOF
Response.Write vbTab & "<TR>" & vbCrLf
For Each Field in rsCount.Fields
Response.Write vbTab & vbTab & "<TD BGCOLOR="""

' Decide what color to output


If bColor Then
Response.Write "#CCCCFF" ' Light blueish
Else
Response.Write "#FFFFFF" ' White
End If

Response.Write """>" & Field.Value & "</TD>" &


vbCrLf
Next 'Field

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 34 de 93

Response.Write vbTab & "</TR>" & vbCrLf

' Toggle our colors


bColor = Not bColor
rsCount.MoveNext
Loop

' End the table


Response.Write "</TABLE>" & vbCrLf
Response.Write "<BR><A HREF=""db_count.asp"">Hide the table</A>" &
vbCrLf
Else
Response.Write "<BR><A HREF=""db_count.asp?showtable=true"">Show
the table</A>" & vbCrLf
End If
' END TABLE DISPLAY - Now back to our regularly scheduled code!
'======================================================================

' Close and dispose of recordset object


rsCount.Close
Set rsCount = Nothing
%>

I wrote this sample to answer the question that I'm sure has been on everyone's mind: "How long can an ASP
reference site go before putting up a sample hit counter script?" Well whatever the old record was I think we
probably shattered it! I've finally broken down and decided to write one. It's pretty simplistic and doesn't
really show off the power of ASP, but what do you want... after all it is just a counter!

It stores it's value in a textfile and counts each request. I didn't bother with a session count. If you're interested
in that see my article "Counting Active Users!" and just remove the line that decrements the count!

What I did do is take into account some of the things that you might want in a hit counter. First of all you can
use this script two different ways. You can cut and paste it into the page you want the count to appear on or
you can use it as an include file and just place one line of text in the document where you want the count to
appear. The text should look something like this:
<!-- #INCLUDE FILE="counter.asp" -->
One thing to note about using this syntax is that the count file it creates will be wherever the file doing the
including is located and this is not necessarily where the script is located! This may be confusing at first, but it
allows you to include the same file and run multiple independent counters on different pages with only one set
of the code!

Another thing to note is that it'll create it's own file to keep track of the count if it doesn't find one. This makes
it pretty darn easy to install. The main problem you might run into is if NTFS permissions don't allow the
anonymous internet user to write to the counter.txt file. Once you get any NTFS issues straightened out all
should be right with the world!

The last thing that bears mentioning is that, as it stands, the script will let you choose either plain text or a set
of images. You can toggle this by setting the images querystring parameter to true or false. If you always use
one or the other it probably makes sense to hard code the value in, but for illustration and flexability I let you
change it on the fly. And for those of you who actually care (and are still reading this) the default is to use
text.
<%
' Declare our vaiables
Dim objFSO, objCountFile ' object vars for FSO and File
Dim strCountFileName ' filename of count text file

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 35 de 93

Dim iCount ' count variable


Dim bUseImages ' boolean whether or not to use images
Dim I ' standard looping var

' Determine whether we use images or plain text


' You could just set this to True or False instead
bUseImages = CBool(Request.QueryString("images"))

' Compute our count file's filename


' This is based on the file from which you call count.asp
' It basically takes that name and appends a .cnt so I don't
' accidently overwrite any files. If for some reason you have
' a file named script_name.asp.cnt then change this or watch out!
strCountFileName = Server.MapPath(Request.ServerVariables("SCRIPT_NAME")
& ".cnt")

' Create FileSystemObject to deal with file access


Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

' Open the file as a text stream (1 = ForReading, True = Create)


Set objCountFile = objFSO.OpenTextFile(strCountFileName, 1, True)

' Read the current count from the file


If Not objCountFile.AtEndOfStream Then
' Set value to contents of the file
iCount = CLng(objCountFile.ReadAll)
Else
' If no file exists or it's empty start at 0
iCount = 0
End If

' Close the file and destroy the object


objCountFile.Close
Set objCountFile = Nothing

' Increment the count


iCount = iCount + 1

' Overwrite existing file and get a text stream to new one
Set objCountFile = objFSO.CreateTextFile(strCountFileName, True)

' Write updated count


objCountFile.Write iCount

' Close the file and destroy the object


objCountFile.Close
Set objCountFile = Nothing

' Destroy the FSO object


Set objFSO = Nothing

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 36 de 93

' We're all done with the hard part


' All that's left is to display the results
If bUseImages Then
' Loop through the count integer showing each digit
' You can grab the images one at a time or get the zip
' http://www.asp101.com/samples/download/counter_imgs.zip
For I = 1 to Len(iCount)
' Output the IMG tag using the right digit
Response.Write "<IMG SRC=""./images/digit_"
Response.Write Mid(iCount, I, 1)
Response.Write ".gif"" ALT="""
Response.Write Mid(iCount, I, 1)
Response.Write """ WIDTH=""20"" HEIGHT=""27"">"
Next 'I
Else
' No image wanted just show the variable
Response.Write iCount
End If
%>

P/ adionar um cookies

Cookie to add:
Cookie Name:
Cookie Value:

Set Cookie

HTML gerado pelo ASP

<FORM ACTION="cookie_write.asp" METHOD=GET>


<INPUT TYPE=HIDDEN NAME="ToDo" VALUE="add">
<B>Cookie to add:</B>
<TABLE>
<TR>
<TD>Cookie Name:</TD>
<TD><INPUT TYPE=TEXT NAME="CookieName"></TD>
</TR>
<TR>
<TD>Cookie Value:</TD>
<TD><INPUT TYPE=TEXT NAME="CookieValue"></TD>
</TR>
<TR>
<TD COLSPAN=2><INPUT TYPE=SUBMIT Value="Set Cookie"></TD>
</TR>
</TABLE>
<FORM

<%
If Request.QueryString("CookieName") <> "" Then
Response.Cookies(Request.QueryString("CookieName")) =
Request.QueryString("CookieValue")
If Request.QueryString("ToDo")= "add" Then

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 37 de 93

Response.Cookies(Request.QueryString("CookieName")).Expires =
Date() + 1
Else

Response.Cookies(Request.QueryString("CookieName")).Expires =
Date() - 1
End If
End If
Response.Redirect("./cookie.asp")
%>

This table lists all of our cookies on your computer.


Cookie Name Cookie Value
Add a cookie to your machine.
Delete a cookie from your machine.

Sample HTML Code generated by the ASP:

This table lists all of our cookies on your computer.


<TABLE WIDTH=100% BORDER=2>
<THEAD>
<TH ALIGN=LEFT>Cookie Name</TH>
<TH ALIGN=LEFT>Cookie Value</TH>
</THEAD>

<TR>
<TD>
Cookie
</TD>
<TD>
Value
</TD>
</TR>

</TABLE>

ASP Source Code:

This table lists all of our cookies on your computer.


<TABLE WIDTH=100% BORDER=2>
<THEAD>
<TH ALIGN=LEFT>Cookie Name</TH>
<TH ALIGN=LEFT>Cookie Value</TH>
</THEAD>
<%
Dim Item
%>
<% For Each Item in Request.Cookies %>
<TR>
<TD>
<% = Item %>
</TD>
<TD>
<% = Request.Cookies(Item) %>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 38 de 93

</TD>
</TR>
<% Next %>
</TABLE>

<A HREF="./cookie_add.asp">Add a cookie to your machine.</A><BR>


<A HREF="./cookie_del.asp">Delete a cookie from your machine.</A><BR>

Script Output:

Results of SELECT * FROM sample WHERE (Sales <> 0) ORDER BY last_name;


id last_name first_name sales
6 Andersen David 6420
3 Buchanan Steven 3245
10 Callahan Laura 3675
13 Dodsworth Nancy 2750
7 Edwards Frank 3840
1 Fuller Andrew 5000
16 Graham Chris 4050
15 Hopkins Peter 6710
21 Ingraham Owen 4750
9 Jones Edward 3450
5 King Robert 5290
2 Leverling Janet 6250
11 Miller Greg 5640
14 Nelson Beth 4345
18 Ostrander Ian 3965
4 Peacock Margaret 4685
19 Quinn Howard 5865
8 Richards Kate 4260
20 Smith Fred 6370
12 Steel Tammy 3570
17 Thompson Vincent 4820
25 Underwood Debra 3790
24 Valentino Linda 2965
27 White Mark 4500
26 Xavier Simon 5580
22 Youngs Quincy 4420
23 Zimmerman Walter 4980

Build your own query:


  4500
Sales: Less Than Greater Than

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 39 de 93

Sort By:
Run Query

Sample HTML Code generated by the ASP:

<B>Results of SELECT Salesmen.* FROM Salesmen WHERE (Sales <> 0) ORDER BY


[Last Name];</B><BR>

<BR>
<TABLE BORDER=1>
<THEAD>

<TH>ID</TH>

<TH>Last Name</TH>

<TH>First Name</TH>

<TH>Sales</TH>

</THEAD>

<TR>

<TD>4</TD>

<TD>Buchanan</TD>

<TD>Steven</TD>

<TD>3245</TD>

</TR>

<TR>

<TD>7</TD>

<TD>Callahan</TD>

<TD>Laura</TD>

<TD>3670</TD>

</TR>

<TR>

<TD>2</TD>

<TD>Davolio</TD>

<TD>Nancy</TD>

<TD>2750</TD>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 40 de 93

</TR>

<TR>

<TD>8</TD>

<TD>Dodsworth</TD>

<TD>Anne</TD>

<TD>4385</TD>

</TR>

<TR>

<TD>11</TD>

<TD>Franken</TD>

<TD>Peter</TD>

<TD>4050</TD>

</TR>

<TR>

<TD>1</TD>

<TD>Fuller</TD>

<TD>Andrew</TD>

<TD>5000</TD>

</TR>

<TR>

<TD>9</TD>

<TD>King</TD>

<TD>Robert</TD>

<TD>5290</TD>

</TR>

<TR>

<TD>10</TD>

<TD>Labrune</TD>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 41 de 93

<TD>Janine</TD>

<TD>3960</TD>

</TR>

<TR>

<TD>3</TD>

<TD>Leverling</TD>

<TD>Janet</TD>

<TD>6250</TD>

</TR>

<TR>

<TD>6</TD>

<TD>Peacock</TD>

<TD>Margaret</TD>

<TD>4685</TD>

</TR>

<TR>

<TD>12</TD>

<TD>Snyder</TD>

<TD>Howard</TD>

<TD>5860</TD>

</TR>

<TR>

<TD>5</TD>

<TD>Suyama</TD>

<TD>Michael</TD>

<TD>4820</TD>

</TR>

</TABLE>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 42 de 93

ASP Source Code:

<%
Dim DataConn, cmdDC, rsDC
Dim Item
Dim iFieldCount, iLoopVar
Dim strLTorGT, iCriteria, strSortBy, strOrder

' Retrieve QueryString Variables and convert them to a usable form


strLTorGT = Request.QueryString("LTorGT")
Select Case strLTorGT
Case "LT"
strLTorGT = "<"
Case "GT"
strLTorGT = ">"
Case Else
strLTorGT = "<>"
End Select

iCriteria = Request.QueryString("criteria")
If IsNumeric(iCriteria) Then
iCriteria = CLng(iCriteria)
Else
iCriteria = 0
End If

strSortBy = Request.QueryString("sortby")
If strSortBy = "" Then strSortBy = "last_name"

strOrder = Request.QueryString("order")
' Finally we've got all our info, now to the cool stuff

' Create and establish data connection


Set DataConn = Server.CreateObject("ADODB.Connection")
DataConn.ConnectionTimeout = 15
DataConn.CommandTimeout = 30

'Access connection code


'DataConn.Open "DBQ=" & Server.MapPath("database.mdb") &
";Driver={Microsoft Access Driver
(*.mdb)};DriverId=25;MaxBufferSize=8192;Threads=20;", "username",
"password"

'Our SQL Server code - use above line to use sample on your server
DataConn.Open Application("SQLConnString"), Application("SQLUsername"),
Application("SQLPassword")

' Create and link command object to data connection then set attributes
and SQL query
Set cmdDC = Server.CreateObject("ADODB.Command")
cmdDC.ActiveConnection = DataConn
cmdDC.CommandText = "SELECT * FROM sample WHERE (Sales " & strLTorGT & "
" & iCriteria & ") ORDER BY " & strSortBy & strOrder & ";"
cmdDC.CommandType = 1

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 43 de 93

' Create recordset and retrieve values using command object


Set rsDC = Server.CreateObject("ADODB.Recordset")
' Opening record set with a forward-only cursor (the 0) and in read-only
mode (the 1)
rsDC.Open cmdDC, , 0, 1
%>

<B>Results of <%= cmdDC.CommandText %></B><BR>

<BR>
<TABLE BORDER=1>
<THEAD>
<% For Each Item in rsDC.Fields %>
<TH><%= Item.Name %></TH>
<% Next %>
</THEAD>
<%
' Loop through recordset and display results
If Not rsDC.EOF Then rsDC.MoveFirst

' Get the number of fields and subtract one so our loops start at 0
iFieldCount = rsDC.Fields.Count - 1

' Continue till we get to the end, and while in each <TR> loop through
fields
Do While Not rsDC.EOF
%> <TR>
<% For iLoopVar = 0 to iFieldCount %>
<TD><%= rsDC.Fields(iLoopVar) %></TD>
<% Next %>
</TR>
<%
rsDC.MoveNext
Loop
%>
</TABLE>

<%
' Close Data Access Objects and free DB variables
rsDC.Close
Set rsDC = Nothing
' can't do a "cmdDC.Close" !
Set cmdDC = Nothing
DataConn.Close
Set DataConn = Nothing
%>

<BR>

<B>Build your own query:</B>


<FORM ACTION="database.asp" METHOD="get">
Sales:
<INPUT TYPE="radio" NAME="LTorGT" VALUE="LT" CHECKED>Less
Than</INPUT>
<INPUT TYPE="radio" NAME="LTorGT" VALUE="GT">Greater Than</INPUT>
<INPUT TYPE="text" NAME="criteria" VALUE="4500" SIZE=10></INPUT>
<BR>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 44 de 93

Sort By:
<SELECT NAME="sortby">
<OPTION VALUE="id">ID
<OPTION VALUE="last_name">Last Name
<OPTION VALUE="first_name">First Name
<OPTION VALUE="sales">Sales
</SELECT>
<SELECT NAME="order">
<OPTION VALUE="">Ascending
<OPTION VALUE=" DESC">Descending
</SELECT>
<BR>
<INPUT TYPE="submit" VALUE="Run Query"></INPUT>
</FORM>

Script Output:

id text_field integer_field date_time_field


43087 Friday 17 9/17/99 12:12:33 PM
43088 Friday 17 9/17/99 12:14:00 PM
43089 Friday 17 9/17/99 12:17:01 PM
43090 Friday 17 9/17/99 12:17:23 PM
43091 Friday 17 9/17/99 12:17:47 PM
43092 Friday 17 9/17/99 12:18:42 PM
43093 Friday 17 9/17/99 12:19:14 PM
Record id 43093 added!

The last record in the table above was just added when you loaded this page!
Click here to add another record to the database.

This is the first in a set of 3 database samples. The series will cover, inserting, deleting, and updating a table
in a database. Being the first of the three, this one is commented the most heavily and should be read before
the other two since much of the code is similar between the three. As with all our samples, these are placed
here as a service to our readers and as a learning aid. They are not necessarily ready for live use on your site
and you should thoroughly test them if you intend to use them on your site. This set of three especially is
placed here to show you one way to accomplish the tasks covered. There are other methods which may give
you better performance and scalability based upon your particular situation.

Another thing to note is that in order to keep this database reasonable, the script automatically purges old
records when the database reaches about a dozen records. If you see entries disappear, appear, or change, it is
most likely due to the fact that you've reached this limit. Please note that it is also likely that others may be
viewing either this sample or one of the other two samples which share the same table in the database at the
same time you are viewing this one. This also will cause changes to the database resulting in entries which
you may not be expecting to see. Ah, the wonderful world of concurrent users!

ASP Source Code:

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 45 de 93

<%' Defining some constants to make my life easier!


' Begin Constant Definition

' DB Configuration constants


' Fake const so we can use the MapPath to make it relative.
' After this, strictly used as if it were a Const.
Dim DB_CONNECTIONSTRING
DB_CONNECTIONSTRING = "DRIVER={Microsoft Access Driver
(*.mdb)};DBQ=" & Server.Mappath("./db_scratch.mdb") & ";"
' We don't use these, but we could if we neeeded to.
'Const DB_USERNAME = "username"
'Const DB_PASSWORD = "password"

'Now we override the above settings to use our SQL server.


'Delete the following line to use the sample Access DB.
DB_CONNECTIONSTRING = Application("SQLConnString") & "UID=" &
Application("SQLUsername") & ";PWD=" & Application("SQLPassword") & ";"

' ADODB Constants


' You can find these in the adovbs.inc file
' Do a search for it and it should turn up somewhere on the server
' If you can't find it you can download our copy from here:
' http://www.asp101.com/samples/download/adovbs.inc
' It may not be the most recent copy so use it at your own risk.
%>
<!-- #INCLUDE FILE="adovbs.inc" -->
<%
' End Constant Definition
%>

<%
Dim I ' Standard looping var
Dim iRecordAdded ' Id of added record
Dim iRecordCount ' Used only to keep a current count of records for DB
Clean Up

'We're going to keep this as simple as we can.


' 1. Create a Recordset object
' 2. Connect the Recordset to the table
' 3. Add a new record to the Recordset
' 4. Set the values of the Recordset
' 5. Update the table
' 6. Close the Recordset

'Step 1:
Dim objRecordset
Set objRecordset = Server.CreateObject("ADODB.Recordset")

' The following syntax is also acceptable if you move it outside


of the
' script delimiters. I prefer to Dim and then set it like any
other
' variable, but it really doesn't make too big a difference.

'<OBJECT RUNAT=server PROGID=ADODB.Recordset


ID=objRecordset></OBJECT>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 46 de 93

'Step 2:
' The syntax for the open command is
' recordset.Open Source, ActiveConnection, CursorType, LockType,
Options
'
' Source
' In this case it's our Table Name. It could also be a SQL
statement, a
' command object, or a stored procedure.
' ActiveConnection
' We use a string which contains connection information. It
could also
' be a connection object which is faster if you need to open
multiple
' recordsets.
' CursorType
' Doesn't matter too much in this case since I'm not going to be
doing
' much with the records. I'm opening it as a static so I can
get a
' recordcount.
' LockType
' Specifies how the provider should lock the data. We'll use
pessimistic
' so that it'll lock as soon as we start editing and basically
ensure a
' successful update.
' Options
' Tells what type of source we're using if it's not a command
object
'
' Most of the above are optional to some degree. It's usually
better
' to set them so you know what their settings are. It'll avoid
the
' defaults coming back to haunt you when you try and do something
they
' don't allow.

' This is the way I normally would open this RS:


objRecordset.Open "scratch", DB_CONNECTIONSTRING, adOpenStatic,
adLockPessimistic, adCmdTable

' You could also do it step by step if you want:


'objRecordset.Source = "table_name"
'objRecordset.ActiveConnection = DB_CONNECTIONSTRING
'objRecordset.CursorType = adOpenStatic
'objRecordset.LockType = adLockPessimistic
'objRecordset.Open

'Step 3:
' To add a new record to the current recordset we naturally call
the
' AddNew Method.
objRecordset.AddNew

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 47 de 93

' If you're not sure if your RS supports Adding a New record you
can check
' via the following command. This will return True if it does,
False
' otherwise:
' objRecordset.Supports(adAddNew)

' Another Note: It takes arrays as input and gets confusing so I


usually
' don't do it, but you can actually specify the values on the
AddNew line
' (combining steps 3 and 4) like this:
' objRecordset.AddNew Array("text_field", "integer_field",
"date_time_field"), Array("Some Text", CInt(Day(Date())), Now())

'Step 4:
' Here we set the values of each field. You'll notice we don't
set the
' id field. Since it's the primary key, I've set it as an
autonumber in
' the DB so it'll take care of creating the value for us.

' I'm just pulling any values I want for insertion here. You'd
probably use
' something from a form or other user input. Just make sure
you're putting
' the right types of data into the fields.

' String / Text Data Type


objRecordset.Fields("text_field") =
CStr(WeekdayName(WeekDay(Date())))

' Integer Data Type


objRecordset.Fields("integer_field") = CInt(Day(Now()))

' Date / Time Data Type


objRecordset.Fields("date_time_field") = Now()

'Step 5:
' Couldn't be too much easier:
objRecordset.Update

'Show Table
' Feel free to skip this area. (Ignore the man behind the
curtain!)
' I'm just showing the RS so you have something to look at when
' you view the sample.

'Get and store for later Administrative Clean Up


iRecordCount = objRecordset.RecordCount

Response.Write "<TABLE BORDER=""1"" CELLSPACING=""2""


CELLPADDING=""2"">" & vbCrLf
Response.Write vbTab & "<TR>" & vbCrLf
Response.Write vbTab & vbTab & "<TD><B>id</B></TD>" & vbCrLf
Response.Write vbTab & vbTab & "<TD><B>text_field</B></TD>" &
vbCrLf

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 48 de 93

Response.Write vbTab & vbTab & "<TD><B>integer_field</B></TD>" &


vbCrLf
Response.Write vbTab & vbTab & "<TD><B>date_time_field</B></TD>" &
vbCrLf
Response.Write vbTab & "</TR>" & vbCrLf

If Not objRecordset.EOF Then


objRecordset.MoveFirst
'Show data
Do While Not objRecordset.EOF
Response.Write vbTab & "<TR>" & vbCrLf
For I = 0 To objRecordset.Fields.Count - 1
Response.Write vbTab & vbTab & "<TD>" &
objRecordset.Fields(I) & "</TD>" & vbCrLf
iRecordAdded = objRecordset.Fields("id")
Next
Response.Write vbTab & "</TR>" & vbCrLf
objRecordset.MoveNext
Loop
End If
Response.Write "</TABLE>" & vbCrLf

Response.Write "Record id " & iRecordAdded & " added!"

'Now back to our regularly scheduled program!

'Step 6:
' Finally we close the recordset and release the memory used by
the
' object variable by setting it to Nothing (a VBScript keyword)
objRecordset.Close
Set objRecordset = Nothing

'********************************
' This is the end of the sample!
'********************************

' Now this is REALLY behind the curtain!

' Normally I'd cut you off right here and do the rest behind the scenes;
however,
' since this has to do with the DB you were just writing to, I'll give
you a
' treat and let you see some of our administative / housekeeping code!

' Now we clean up!


' Basically, to keep things manageable, I'm checking the DB to keep it
under
' a dozen or so records.
If iRecordCount >= 12 Then
Dim objCleanUpRS
Set objCleanUpRS = Server.CreateObject("ADODB.Recordset")

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 49 de 93

objCleanUpRS.Open "scratch", DB_CONNECTIONSTRING, adOpenDynamic,


adLockPessimistic, adCmdTable

For I = 1 to 10
objCleanUpRS.MoveFirst
objCleanUpRS.Delete
Next

objCleanUpRS.Close
Set objCleanUpRS = Nothing
End If
%>

Sample HTML Code generated by the ASP:

<TABLE BORDER="1" CELLSPACING="2" CELLPADDING="2">


<TR>
<TD><B>id</B></TD>
<TD><B>text_field</B></TD>
<TD><B>integer_field</B></TD>
<TD><B>date_time_field</B></TD>
</TR>
<TR>
<TD>132</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 7:56:35 PM</TD>
</TR>
<TR>
<TD>133</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 7:56:36 PM</TD>
</TR>
<TR>
<TD>134</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 7:56:37 PM</TD>
</TR>
<TR>
<TD>135</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 7:57:02 PM</TD>
</TR>
<TR>
<TD>136</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 8:04:36 PM</TD>
</TR>
<TR>
<TD>137</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 8:05:14 PM</TD>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 50 de 93

</TR>
<TR>
<TD>138</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 8:07:25 PM</TD>
</TR>
<TR>
<TD>139</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 8:08:46 PM</TD>
</TR>
</TABLE>
Record id 139 added!

Script Output:

id text_field integer_field date_time_field


43088 Friday 17 9/17/99 12:14:00 PM
43089 Friday 17 9/17/99 12:17:01 PM
43090 Friday 17 9/17/99 12:17:23 PM
43091 Friday 17 9/17/99 12:17:47 PM
43092 Friday 17 9/17/99 12:18:42 PM
43093 Friday 17 9/17/99 12:19:14 PM
43094 Friday 17 9/17/99 12:21:40 PM
Record id 43087 deleted!

Click here to delete the oldest record in the database.

This is the number two in our set of 3 database editing samples. If you have any questions about this sample,
please check out the first in the series here as it is the most heavily commented. Both this and part three
assume you've already checked out the first script since much of the code is similar between the three.

ASP Source Code:

<%' Defining some constants to make my life easier! (Same as Sample 1)


' Begin Constant Definition

' DB Configuration constants


' Fake const so we can use the MapPath to make it relative.
' After this, strictly used as if it were a Const.
Dim DB_CONNECTIONSTRING
DB_CONNECTIONSTRING = "DRIVER={Microsoft Access Driver
(*.mdb)};DBQ=" & Server.Mappath("./db_scratch.mdb") & ";"
' We don't use these, but we could if we neeeded to.

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 51 de 93

'Const DB_USERNAME = "username"


'Const DB_PASSWORD = "password"

'Now we override the above settings to use our SQL server.


'Delete the following line to use the sample Access DB.
DB_CONNECTIONSTRING = Application("SQLConnString") & "UID=" &
Application("SQLUsername") & ";PWD=" & Application("SQLPassword") & ";"

' ADODB Constants


' You can find these in the adovbs.inc file
' Do a search for it and it should turn up somewhere on the server
' If you can't find it you can download our copy from here:
' http://www.asp101.com/samples/download/adovbs.inc
' It may not be the most recent copy so use it at your own risk.
%>
<!-- #INCLUDE FILE="adovbs.inc" -->
<%
' End Constant Definition
%>

<%
Dim I ' Standard looping var
Dim iRecordDeleted ' Id of deleted record
Dim iRecordCount ' Used only to keep a current count of records for DB
Clean Up

'We're going to keep this as simple as we can.


' 1. Create a Recordset object
' 2. Connect the Recordset to the table
' 3. Find the record to delete
' 4. Delete It!
' 5. Update the table
' 6. Close the Recordset

'Step 1:
Dim objRecordset
Set objRecordset = Server.CreateObject("ADODB.Recordset")

'Step 2:
' The syntax for the open command is
' recordset.Open Source, ActiveConnection, CursorType, LockType,
Options
objRecordset.Open "scratch", DB_CONNECTIONSTRING, adOpenStatic,
adLockPessimistic, adCmdTable

'Step 3:
' Not really much to do here!
' We're looking to delete the oldest record from the current
recordset.
' Since we add them in order, the first one is the one to delete.

' Note: If the data was a little more important (or of any value
at all
' to us!), we'd probably check some other criteria or at least
check to see
' if it's the oldest record in the recordset. Since it's not and
we really

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 52 de 93

' don't care, here goes!

'Step 4:
'Get and store for later Administrative Clean Up
iRecordCount = objRecordset.RecordCount

'Only delete if they press the delete link!


If Request.QueryString("action") = "delete" Then
If Not objRecordset.EOF Then
objRecordset.MoveFirst
iRecordDeleted = objRecordset.Fields("id")
objRecordset.Delete adAffectCurrent
' You can also delete groups of records which
satisfy the filter
' property setting if you're doing this in batch
mode. For this
' situation we're just killing the one record so
we don't bother.
End If
End If

'Step 5:
' We don't need to do the update unless we batch it like mentioned
above!
'objRecordset.UpdateBatch

' I do this just to be sure we don't display the deleted record!


' It's really not needed. The records gone from the DB, but may
still
' be hanging around in our RS.
objRecordset.Requery

'Show Table
' Feel free to skip this area. (Ignore the man behind the
curtain!)
' I'm just showing the RS so you have something to look at when
' you view the sample.

'Get and store for later Administrative Clean Up


iRecordCount = objRecordset.RecordCount

Response.Write "<TABLE BORDER=""1"" CELLSPACING=""2""


CELLPADDING=""2"">" & vbCrLf
Response.Write vbTab & "<TR>" & vbCrLf
Response.Write vbTab & vbTab & "<TD><B>id</B></TD>" & vbCrLf
Response.Write vbTab & vbTab & "<TD><B>text_field</B></TD>" &
vbCrLf
Response.Write vbTab & vbTab & "<TD><B>integer_field</B></TD>" &
vbCrLf
Response.Write vbTab & vbTab & "<TD><B>date_time_field</B></TD>" &
vbCrLf
Response.Write vbTab & "</TR>" & vbCrLf
If Not objRecordset.EOF Then
objRecordset.MoveFirst
'Show data
Do While Not objRecordset.EOF
Response.Write vbTab & "<TR>" & vbCrLf

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 53 de 93

For I = 0 To objRecordset.Fields.Count - 1
Response.Write vbTab & vbTab & "<TD>" &
objRecordset.Fields(I) & "</TD>" & vbCrLf
Next
Response.Write vbTab & "</TR>" & vbCrLf
objRecordset.MoveNext
Loop
End If
Response.Write "</TABLE>" & vbCrLf

If iRecordDeleted <> 0 Then Response.Write "Record id " &


iRecordDeleted & " deleted!"

'Now back to our regularly scheduled program!

'Step 6:
' Finally we close the recordset and release the memory used by
the
' object variable by setting it to Nothing (a VBScript keyword)
objRecordset.Close
Set objRecordset = Nothing

'********************************
' This is the end of the sample!
'********************************

' Now this is REALLY behind the curtain!

' Normally I'd cut you off right here and do the rest behind the scenes;
however,
' since this has to do with the DB you were just writing to, I'll give
you a
' treat and let you see some of our administative / housekeeping code!

' Now we clean up!


' Basically, to keep things manageable, I'm checking the DB to keep it
over
' 2 records.
If iRecordCount <= 2 Then
Dim objCleanUpRS
Set objCleanUpRS = Server.CreateObject("ADODB.Recordset")

objCleanUpRS.Open "scratch", DB_CONNECTIONSTRING, adOpenStatic,


adLockPessimistic, adCmdTable

For I = 1 to 2
objCleanUpRS.AddNew
objCleanUpRS.Fields("text_field") =
CStr(WeekdayName(WeekDay(Date())))
objCleanUpRS.Fields("integer_field") = CInt(Day(Now()))
objCleanUpRS.Fields("date_time_field") = Now()
Next
objCleanUpRS.Update

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 54 de 93

objCleanUpRS.Close
Set objCleanUpRS = Nothing
End If
%>

Sample HTML Code generated by the ASP:

<TABLE BORDER="1" CELLSPACING="2" CELLPADDING="2">


<TR>
<TD><B>id</B></TD>
<TD><B>text_field</B></TD>
<TD><B>integer_field</B></TD>
<TD><B>date_time_field</B></TD>
</TR>
<TR>
<TD>178</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 9:24:31 PM</TD>
</TR>
<TR>
<TD>179</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 9:24:36 PM</TD>
</TR>
<TR>
<TD>180</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 9:25:04 PM</TD>
</TR>
<TR>
<TD>181</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 9:25:34 PM</TD>
</TR>
<TR>
<TD>182</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 9:25:38 PM</TD>
</TR>
<TR>
<TD>183</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 9:26:13 PM</TD>
</TR>
<TR>
<TD>184</TD>
<TD>Tuesday</TD>
<TD>19</TD>
<TD>1/19/99 9:26:21 PM</TD>
</TR>
</TABLE>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 55 de 93

Record id 177 deleted!

Script Output:

id text_field integer_field date_time_field


43088 Friday 17 9/17/99 12:14:00 PM
43089 Friday 17 9/17/99 12:17:01 PM
43090 Friday 17 9/17/99 12:17:23 PM
43091 Friday 17 9/17/99 12:25:05 PM
43092 Friday 17 9/17/99 12:18:42 PM
43093 Friday 17 9/17/99 12:19:14 PM
43094 Friday 17 9/17/99 12:21:40 PM
43095 Friday 17 9/17/99 12:22:57 PM
43096 Friday 17 9/17/99 12:23:23 PM
Record id 43091 updated!

Click on any hyperlink above to update the corresponding record in the database.
ASP Source Code:

<%' Defining some constants to make my life easier! (Same as Sample 1 &
2)
' Begin Constant Definition

' DB Configuration constants


' Fake const so we can use the MapPath to make it relative.
' After this, strictly used as if it were a Const.
Dim DB_CONNECTIONSTRING
DB_CONNECTIONSTRING = "DRIVER={Microsoft Access Driver
(*.mdb)};DBQ=" & Server.Mappath("./db_scratch.mdb") & ";"
' We don't use these, but we could if we neeeded to.
'Const DB_USERNAME = "username"
'Const DB_PASSWORD = "password"

'Now we override the above settings to use our SQL server.


'Delete the following line to use the sample Access DB.
DB_CONNECTIONSTRING = Application("SQLConnString") & "UID=" &
Application("SQLUsername") & ";PWD=" & Application("SQLPassword") & ";"

' ADODB Constants


' You can find these in the adovbs.inc file
' Do a search for it and it should turn up somewhere on the server
' If you can't find it you can download our copy from here:
' http://www.asp101.com/samples/download/adovbs.inc
' It may not be the most recent copy so use it at your own risk.
%>
<!-- #INCLUDE FILE="adovbs.inc" -->
<%

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 56 de 93

' End Constant Definition


%>

<%
Dim I ' Standard looping var
Dim iRecordToUpdate ' Id of deleted record

'We're going to keep this as simple as we can.


' 1. Create a Recordset object
' 2. Connect the Recordset to the table
' 3. Find the record to update
' 4. Update the record
' 5. Update the table
' 6. Close the Recordset

'Step 1:
Dim objRecordset
Set objRecordset = Server.CreateObject("ADODB.Recordset")

'Step 2:
' The syntax for the open command is
' recordset.Open Source, ActiveConnection, CursorType, LockType,
Options
objRecordset.Open "scratch", DB_CONNECTIONSTRING, adOpenStatic,
adLockPessimistic, adCmdTable

'Step 3:
iRecordToUpdate = CLng(Request.QueryString("id"))

If iRecordToUpdate <> 0 Then


If Not objRecordset.EOF Then
objRecordset.MoveFirst
Do Until objRecordset.Fields("id") =
iRecordToUpdate
objRecordset.MoveNext
Loop

'Step 4:
'Only update if they've told us to, o/w we never run this

' String / Text Data Type


objRecordset.Fields("text_field") =
CStr(WeekdayName(WeekDay(Date())))

' Integer Data Type


objRecordset.Fields("integer_field") =
CInt(Day(Now()))

' Date / Time Data Type


objRecordset.Fields("date_time_field") = Now()

'Step 5:
'Only update if they've told us to, o/w we never run this
objRecordset.Update
End If
End If

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 57 de 93

'Show Table
' Feel free to skip this area. (Ignore the man behind the
curtain!)
' I'm just showing the RS so you have something to look at when
' you view the sample.

Response.Write "<TABLE BORDER=""1"" CELLSPACING=""2""


CELLPADDING=""2"">" & vbCrLf
Response.Write vbTab & "<TR>" & vbCrLf
Response.Write vbTab & vbTab & "<TD><B>id</B></TD>" & vbCrLf
Response.Write vbTab & vbTab & "<TD><B>text_field</B></TD>" &
vbCrLf
Response.Write vbTab & vbTab & "<TD><B>integer_field</B></TD>" &
vbCrLf
Response.Write vbTab & vbTab & "<TD><B>date_time_field</B></TD>" &
vbCrLf
Response.Write vbTab & "</TR>" & vbCrLf
If Not objRecordset.EOF Then
objRecordset.MoveFirst
'Show data
Do While Not objRecordset.EOF
Response.Write vbTab & "<TR>" & vbCrLf
For I = 0 To objRecordset.Fields.Count - 1
Response.Write vbTab & vbTab & "<TD><A
HREF=""db_update.asp?id=" & objRecordset.Fields("id") & """>" &
objRecordset.Fields(I) & "</A></TD>" & vbCrLf
Next
Response.Write vbTab & "</TR>" & vbCrLf
objRecordset.MoveNext
Loop
End If
Response.Write "</TABLE>" & vbCrLf

If iRecordToUpdate <> 0 Then Response.Write "Record id " &


iRecordToUpdate & " updated!"

'Now back to our regularly scheduled program!

'Step 6:
' Finally we close the recordset and release the memory used by
the
' object variable by setting it to Nothing (a VBScript keyword)
objRecordset.Close
Set objRecordset = Nothing
%>

Sample HTML Code generated by the ASP:

<TABLE BORDER="1" CELLSPACING="2" CELLPADDING="2">


<TR>
<TD><B>id</B></TD>
<TD><B>text_field</B></TD>
<TD><B>integer_field</B></TD>
<TD><B>date_time_field</B></TD>
</TR>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 58 de 93

<TR>
<TD><A HREF="db_update.asp?id=178">178</A></TD>
<TD><A HREF="db_update.asp?id=178">Tuesday</A></TD>
<TD><A HREF="db_update.asp?id=178">19</A></TD>
<TD><A HREF="db_update.asp?id=178">1/19/99 9:24:31
PM</A></TD>
</TR>
<TR>
<TD><A HREF="db_update.asp?id=179">179</A></TD>
<TD><A HREF="db_update.asp?id=179">Tuesday</A></TD>
<TD><A HREF="db_update.asp?id=179">19</A></TD>
<TD><A HREF="db_update.asp?id=179">1/19/99 9:24:36
PM</A></TD>
</TR>
<TR>
<TD><A HREF="db_update.asp?id=180">180</A></TD>
<TD><A HREF="db_update.asp?id=180">Tuesday</A></TD>
<TD><A HREF="db_update.asp?id=180">19</A></TD>
<TD><A HREF="db_update.asp?id=180">1/19/99 9:25:04
PM</A></TD>
</TR>
<TR>
<TD><A HREF="db_update.asp?id=181">181</A></TD>
<TD><A HREF="db_update.asp?id=181">Tuesday</A></TD>
<TD><A HREF="db_update.asp?id=181">19</A></TD>
<TD><A HREF="db_update.asp?id=181">1/19/99 11:06:38
PM</A></TD>
</TR>
<TR>
<TD><A HREF="db_update.asp?id=182">182</A></TD>
<TD><A HREF="db_update.asp?id=182">Tuesday</A></TD>
<TD><A HREF="db_update.asp?id=182">19</A></TD>
<TD><A HREF="db_update.asp?id=182">1/19/99 11:13:40
PM</A></TD>
</TR>
<TR>
<TD><A HREF="db_update.asp?id=183">183</A></TD>
<TD><A HREF="db_update.asp?id=183">Tuesday</A></TD>
<TD><A HREF="db_update.asp?id=183">19</A></TD>
<TD><A HREF="db_update.asp?id=183">1/19/99 9:26:13
PM</A></TD>
</TR>
<TR>
<TD><A HREF="db_update.asp?id=184">184</A></TD>
<TD><A HREF="db_update.asp?id=184">Tuesday</A></TD>
<TD><A HREF="db_update.asp?id=184">19</A></TD>
<TD><A HREF="db_update.asp?id=184">1/19/99 9:26:21
PM</A></TD>
</TR>
</TABLE>
Record id 182 updated!

Script Output:

Page 1 of 3

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 59 de 93

id last_name first_name sales


1 Fuller Andrew 5000
2 Leverling Janet 6250
3 Buchanan Steven 3245
4 Peacock Margaret 4685
5 King Robert 5290
6 Andersen David 6420
7 Edwards Frank 3840
8 Richards Kate 4260
9 Jones Edward 3450
10 Callahan Laura 3675
Next

Ever wonder how the search engines pull off that cool trick of only showing you the first ten results that your
query pulls back from their gigantic database? Well, rest assured that you're not alone. It's been a popular
request here at ASP 101, and as far as we can tell, everywhere else as well.

We did some research and there are a couple of ways to accomplish this particular trick. Since we're doing
this for the web, one thing we decided was that we didn't want to leave any DB objects hanging around. This
decision might hurt performance if you're going to be doing a lot of paging back and forth, but for us, it
seemed to be worth the performace hit to not have the memory usage from unused DB objects lingering
around in users' session objects.

If you're wondering, the reason we set the page size so small is because our sample DB is tiny and we figured
a single page paging sample wouldn't illustrate the concept too well! The other thing to notice is that, besides
the include at the top, this was all done in script. No context switching at all. I don't know if I like it or not,
but I never felt the need to drop out to HTML and heck it's something else for you to notice!

The final thing I'd like you to notice is something everyone seems to compliain about! Take a look at our
HTML source on this one. By my standards, the table's flawless! Everyone always complains that either their
ASP code looks ugly or the reslting HTML output does. We really can't allow either one since our code is on
public display. I'm showing you that you can get both to be presentable with a little work and some careful
placement of vbCrLf's and vbTab's!

Once again, this is the same DB as our original Database sample. If for some reason you want a copy of the
DB you can download it here.

Take a look through the code. There are some comments, but you'll find the level of sarcasm is lower than
usual. Code, comments, and that's all folks!

ASP Source Code:

<!--VB ADO Constants file. Needed for the ad... constants we use-->
<!-- #INCLUDE FILE="./adovbs.inc" -->
<%
' BEGIN USER CONSTANTS
Dim CONN_STRING
Dim CONN_USER

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 60 de 93

Dim CONN_PASS

' I'm using a DSN-less connection.


' To use a DSN, the format is shown on the next line:
'CONN_STRING = "DSN=DSNName;"

CONN_STRING = "DBQ=" & Server.MapPath("database.mdb") & ";"


CONN_STRING = CONN_STRING & "Driver={Microsoft Access Driver
(*.mdb)};DriverId=25;"

' This DB is unsecured, o/w you'd need to specify something here


CONN_USER = ""
CONN_PASS = ""

'Our SQL code - overriding values we just set - comment out to use Access
CONN_STRING = Application("SQLConnString")
CONN_USER = Application("SQLUsername")
CONN_PASS = Application("SQLPassword")
' END USER CONSTANTS

' BEGIN RUNTIME CODE


' Declare our vars
Dim iPageSize 'How big our pages are
Dim iPageCount 'The number of pages we get back
Dim iPageCurrent 'The page we want to show
Dim sSQL 'SQL command to execute
Dim objPagingConn 'The ADODB connection object
Dim objPagingRS 'The ADODB recordset object
Dim iRecordsShown 'Loop controller for displaying just iPageSize
records
Dim I 'Standard looping var

' Get parameters


iPageSize = 10 ' You could easily allow users to change this

If Request.QueryString("page") = "" Then


iPageCurrent = 1
Else
iPageCurrent = CInt(Request.QueryString("page"))
End If

' Create and open our db connection


Set objPagingConn = Server.CreateObject("ADODB.Connection")
objPagingConn.Open CONN_STRING, CONN_USER, CONN_PASS

' Create recordset


Set objPagingRS = Server.CreateObject("ADODB.Recordset")

' Set page size


objPagingRS.PageSize = iPageSize

' Other settings I was playing with


'objPagingRS.CursorLocation = adUseClient
'objPagingRS.CacheSize = iPageSize

' If you were doing this script with a search or something

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 61 de 93

' you'd need to pass the sql from page to page. I'm just
' paging through the entire table so I just hard coded it.
' What you show is irrelevant to the point of the sample.
sSQL = "SELECT * FROM sample ORDER BY id;"

' Some lines I used while writing to debug... uh "test", yeah that's it!
' Left them FYI.
'sSQL = "SELECT * FROM sample WHERE id=1234 ORDER BY id;"
'sSQL = "SELECT * FROM sample WHERE id > 5 ORDER BY id;"
'sSQL = "SELECT * FROM sample;"
'Response.Write sSQL

' Open RS
objPagingRS.Open sSQL, objPagingConn, adOpenStatic, adLockReadOnly,
adCmdText

' Get the count of the pages using the given page size
iPageCount = objPagingRS.PageCount

' If the request page falls outside the acceptable range,


' give them the closest match (1 or max)
If iPageCurrent > iPageCount Then iPageCurrent = iPageCount
If iPageCurrent < 1 Then iPageCurrent = 1

' Check to prevent bombing when zero results are returned!


If iPageCount = 0 Then
Response.Write "No records found!"
Else
' Move to the selected page
objPagingRS.AbsolutePage = iPageCurrent

' Start output with a page x of n line


%>
<FONT SIZE="+1">
Page <B><%= iPageCurrent %></B> of <B><%= iPageCount %></B>
</FONT>
<%
' Spacing
Response.Write "<BR><BR>" & vbCrLf

' Continue with a title row in our table


Response.Write "<TABLE BORDER=""1"">" & vbCrLf

' Show field names


Response.Write vbTab & "<TR>" & vbCrLf
For I = 0 To objPagingRS.Fields.Count - 1
Response.Write vbTab & vbTab & "<TD><B>"
Response.Write objPagingRS.Fields(I).Name
Response.Write "<B></TD>" & vbCrLf
Next 'I
Response.Write vbTab & "</TR>" & vbCrLf

' Loop through our records


iRecordsShown = 0
Do While iRecordsShown < iPageSize And Not objPagingRS.EOF
Response.Write vbTab & "<TR>" & vbCrLf

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 62 de 93

For I = 0 To objPagingRS.Fields.Count - 1
Response.Write vbTab & vbTab & "<TD>"
Response.Write objPagingRS.Fields(I)
Response.Write "</TD>" & vbCrLf
Next 'I
Response.Write vbTab & "</TR>" & vbCrLf

' Increment the number of records we've shown


iRecordsShown = iRecordsShown + 1
' Can't forget to move to the next record!
objPagingRS.MoveNext
Loop

' All done - close table


Response.Write "</TABLE>" & vbCrLf
End If

' Close DB objects and free variables


objPagingRS.Close
Set objPagingRS = Nothing
objPagingConn.Close
Set objPagingConn = Nothing

' Show "previous" and "next" page links which pass the page to view.
' Could just as easily use form buttons.
If iPageCurrent <> 1 Then

%>
<A HREF="./db_paging.asp?page=<%= iPageCurrent - 1
%>">Previous</A>
&nbsp;&nbsp;
<%
' Above spacing is inside the If so we don't get it unless needed
End If

If iPageCurrent < iPageCount Then


%>
<A HREF="./db_paging.asp?page=<%= iPageCurrent + 1 %>">Next</A>
<%
End If
' END RUNTIME CODE
%>

Sample HTML Code generated by the ASP:

<!--VB ADO Constants file. Needed for the ad... constants we use-->
<FONT SIZE="+1">Page <B>2</B> of <B>3</B></FONT><BR><BR>
<TABLE BORDER="1">
<TR>
<TD><B>PledgeID<B></TD>
<TD><B>DatePledged<B></TD>
<TD><B>AmountPledged<B></TD>
<TD><B>Paid<B></TD>
<TD><B>CardholdersName<B></TD>
</TR>
<TR>
<TD>11</TD>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 63 de 93

<TD>2/1/95</TD>
<TD>45</TD>
<TD>True</TD>
<TD>Karl Jablonski</TD>
</TR>
<TR>
<TD>12</TD>
<TD>2/27/95</TD>
<TD>25</TD>
<TD>True</TD>
<TD>Karl Jablonski</TD>
</TR>
<TR>
<TD>13</TD>
<TD>3/11/95</TD>
<TD>30</TD>
<TD>True</TD>
<TD>Karl Jablonski</TD>
</TR>
<TR>
<TD>14</TD>
<TD>4/1/95</TD>
<TD>75</TD>
<TD>True</TD>
<TD>Karl Jablonski</TD>
</TR>
<TR>
<TD>15</TD>
<TD>4/15/95</TD>
<TD>125</TD>
<TD>False</TD>
<TD>Karl Jablonski</TD>
</TR>
<TR>
<TD>16</TD>
<TD>5/1/95</TD>
<TD>55</TD>
<TD>True</TD>
<TD>Art Braunschweiger</TD>
</TR>
<TR>
<TD>17</TD>
<TD>5/22/95</TD>
<TD>100</TD>
<TD>True</TD>
<TD>Art Braunschweiger</TD>
</TR>
<TR>
<TD>18</TD>
<TD>5/13/95</TD>
<TD>40</TD>
<TD>True</TD>
<TD>Art Braunschweiger</TD>
</TR>
<TR>
<TD>19</TD>
<TD>5/14/95</TD>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 64 de 93

<TD>100</TD>
<TD>True</TD>
<TD>Art Braunschweiger</TD>
</TR>
<TR>
<TD>20</TD>
<TD>6/1/95</TD>
<TD>75</TD>
<TD>True</TD>
<TD>Art Braunschweiger</TD>
</TR>
</TABLE>
<A HREF="./db_paging.asp?page=1">Previous</A>
&nbsp;&nbsp;
<A HREF="./db_paging.asp?page=3">Next</A>

Script Output:

Submit

Everybody wants DataBase samples! What's the deal? You mean not everybody sits around writing ASP code
for the fun of it and to entertain the visitors to their web site! You actually want to talk to a data source and do
something? Why would anyone want to do that!

Well if you insist! This script simply pulls the ID's and names of some imaginary employees from a sales DB
and places them into a pull down box. As all you DB lovers out there know, this means when we update the
list of employees in the DB, our web-page updates itself to include the new entries automatically. No more
going in to change your selections just so people can find the new page which was there to begin with but just
wasn't added to the list! From the pull down, you select the employee you want to see details on and press the
submit button. Then, as if by magic, all the details for that employee appear on the resulting page!

It's a simple enough script and the database is even simpler which sort of explains the lack of any real
usefulness to this sample as is. If you connect it to an employee database with some useful content and cool
pictures or gossip about the employees, it might actually be helpful ( or at least interesting ) to read!

ASP Source Code:

<%
Dim objDC, objRS

' Create and establish data connection


Set objDC = Server.CreateObject("ADODB.Connection")
objDC.ConnectionTimeout = 15
objDC.CommandTimeout = 30

'Use this line to use Access


'objDC.Open "DBQ=" & Server.MapPath("database.mdb") & ";Driver={Microsoft
Access Driver (*.mdb)};DriverId=25;MaxBufferSize=8192;Threads=20;",
"username", "password"

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 65 de 93

'Our SQL Server code - use above line to use sample on your server
objDC.Open Application("SQLConnString"), Application("SQLUsername"),
Application("SQLPassword")

' Create recordset and retrieve values using the open connection
Set objRS = Server.CreateObject("ADODB.Recordset")
' Opening record set with a forward-only cursor (the 0) and in read-only
mode (the 1)

' If a request for a specific id comes in, then do it o/w just show
pulldown
If Len(Request.QueryString("id")) <> 0 Then
' request record for requested id
objRS.Open "SELECT * FROM sample WHERE id=" &
Request.QueryString("id"), objDC, 0, 1
' Show selected record
If Not objRS.EOF Then
objRS.MoveFirst
%>
<TABLE BORDER=2>
<TR>
<TD><B>ID Number</B></TD>
<TD><B>First Name</B></TD>
<TD><B>Last Name</B></TD>
<TD><B>Month's Sales</B></TD>
</TR>
<TR>
<TD ALIGN="center"><%= objRS.Fields("id")
%></TD>
<TD ALIGN="left"><%=
objRS.Fields("first_name") %></TD>
<TD ALIGN="left"><%=
objRS.Fields("last_name") %></TD>
<TD ALIGN="right"><%= objRS.Fields("sales")
%></TD>
</TR>
</TABLE>
<%
End If
objRS.Close
End If

objRS.Open "sample", objDC, 0, 1


' Loop through recordset and display results
If Not objRS.EOF Then
objRS.MoveFirst
' the form below calls this file only this time with an id in the
QueryString
%>
<FORM ACTION="./db_pulldown.asp" METHOD="get">
<SELECT NAME="id">
<OPTION></OPTION>
<%
' Continue until we get to the end of the recordset.
Do While Not objRS.EOF

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 66 de 93

' For each record we create a option tag and set it's
value to the employee id
' The text we set to the employees first name combined
with a space and then their last name
%>
<OPTION VALUE="<%= objRS.Fields("id") %>"><%=
objRS.Fields("first_name") & " " & objRS.Fields("last_name") %></OPTION>
<%
' Get next record
objRS.MoveNext
Loop
%>
</SELECT>
<INPUT type="submit" value="Submit">
</FORM>
<%
End If

' Close Data Access Objects and free DB variables


objRS.Close
Set objRS = Nothing
objDC.Close
Set objDC = Nothing
%>

Sample HTML Code generated by the ASP:

<TABLE BORDER=2>
<TR>
<TD><B>ID Number</B></TD>
<TD><B>First Name</B></TD>
<TD><B>Last Name</B></TD>
<TD><B>Month's Sales</B></TD>
</TR>
<TR>
<TD ALIGN="center">3</TD>
<TD ALIGN="left">Janet</TD>
<TD ALIGN="left">Leverling</TD>
<TD ALIGN="right">6250</TD>
</TR>
</TABLE>

<FORM ACTION="./db_pulldown.asp" METHOD="get">


<SELECT NAME="id">
<OPTION></OPTION>

<OPTION VALUE="1">Andrew Fuller</OPTION>


<OPTION VALUE="2">Nancy Davolio</OPTION>
<OPTION VALUE="3">Janet Leverling</OPTION>
<OPTION VALUE="4">Steven Buchanan</OPTION>
<OPTION VALUE="5">Michael Suyama</OPTION>
<OPTION VALUE="6">Margaret Peacock</OPTION>
<OPTION VALUE="7">Laura Callahan</OPTION>
<OPTION VALUE="8">Anne Dodsworth</OPTION>
<OPTION VALUE="9">Robert King</OPTION>
<OPTION VALUE="10">Janine Labrune</OPTION>
<OPTION VALUE="11">Peter Franken</OPTION>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 67 de 93

<OPTION VALUE="12">Howard Snyder</OPTION>


</SELECT>
<INPUT type="submit" value="Submit">
</FORM>

Script Output:

Hello visitor from 200.255.253.243! Your browser identifies itself as Mozilla/4.0 (compatible; MSIE 5.0;
Windows 98; DigExt).

Server Variable Value


HTTP_ACCEPT:application/vnd.ms-excel, application/msword, application/vnd.ms-
powerpoint, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*
HTTP_ACCEPT_LANGUAGE:pt-br HTTP_CONNECTION:keep-alive
HTTP_HOST:www.asp101.com
HTTP_REFERER:http://www.asp101.com/samples/index.asp
HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)
ALL_HTTP
HTTP_COOKIE:ASPSESSIONIDGQQGQRJA=EFHBIIPDGBGEILKIAIDPFJHN
HTTP_VIA:1.0 GW.RFFSA.GOV.BR:3128 (Squid/2.1.PATCH2), 1.0
cache1.ccard.com.br:80 (Squid/2.2.STABLE1), 1.0 wks03.rjo.embratel.net.br:3128
(Squid/2.2.STABLE3) HTTP_ACCEPT_ENCODING:gzip, deflate
HTTP_X_FORWARDED_FOR:128.1.1.100, 200.244.71.6, unknown
HTTP_CACHE_CONTROL:max-age=259200
Accept: application/vnd.ms-excel, application/msword, application/vnd.ms-
powerpoint, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */* Accept-
Language: pt-br Connection: keep-alive Host: www.asp101.com Referer:
http://www.asp101.com/samples/index.asp User-Agent: Mozilla/4.0 (compatible;
MSIE 5.0; Windows 98; DigExt) Cookie:
ALL_RAW
ASPSESSIONIDGQQGQRJA=EFHBIIPDGBGEILKIAIDPFJHN Via: 1.0
GW.RFFSA.GOV.BR:3128 (Squid/2.1.PATCH2), 1.0 cache1.ccard.com.br:80
(Squid/2.2.STABLE1), 1.0 wks03.rjo.embratel.net.br:3128 (Squid/2.2.STABLE3)
Accept-Encoding: gzip, deflate X-Forwarded-For: 128.1.1.100, 200.244.71.6,
unknown Cache-Control: max-age=259200
APPL_MD_PATH /LM/W3SVC/16/Root
APPL_PHYSICAL_PATH D:\Webs\asp101\
AUTH_PASSWORD
AUTH_TYPE
AUTH_USER
CERT_COOKIE
CERT_FLAGS
CERT_ISSUER
CERT_KEYSIZE
CERT_SECRETKEYSIZE
CERT_SERIALNUMBER
CERT_SERVER_ISSUER
CERT_SERVER_SUBJECT
CERT_SUBJECT

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 68 de 93

CONTENT_LENGTH 0
CONTENT_TYPE
GATEWAY_INTERFACE CGI/1.1
HTTPS off
HTTPS_KEYSIZE
HTTPS_SECRETKEYSIZE
HTTPS_SERVER_ISSUER
HTTPS_SERVER_SUBJECT
INSTANCE_ID 16
INSTANCE_META_PATH /LM/W3SVC/16
LOCAL_ADDR 208.239.225.200
LOGON_USER
PATH_INFO /samples/servvars.asp
PATH_TRANSLATED D:\Webs\asp101\samples\servvars.asp
QUERY_STRING
REMOTE_ADDR 200.255.253.243
REMOTE_HOST 200.255.253.243
REMOTE_USER
REQUEST_METHOD GET
SCRIPT_NAME /samples/servvars.asp
SERVER_NAME www.asp101.com
SERVER_PORT 80
SERVER_PORT_SECURE 0
SERVER_PROTOCOL HTTP/1.0
SERVER_SOFTWARE Microsoft-IIS/4.0
URL /samples/servvars.asp
application/vnd.ms-excel, application/msword, application/vnd.ms-powerpoint,
HTTP_ACCEPT
image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*
HTTP_ACCEPT_LANGUAGE pt-br
HTTP_CONNECTION keep-alive
HTTP_HOST www.asp101.com
HTTP_REFERER http://www.asp101.com/samples/index.asp
HTTP_USER_AGENT Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)
HTTP_COOKIE ASPSESSIONIDGQQGQRJA=EFHBIIPDGBGEILKIAIDPFJHN
1.0 GW.RFFSA.GOV.BR:3128 (Squid/2.1.PATCH2), 1.0 cache1.ccard.com.br:80
HTTP_VIA
(Squid/2.2.STABLE1), 1.0 wks03.rjo.embratel.net.br:3128 (Squid/2.2.STABLE3)
HTTP_ACCEPT_ENCODING gzip, deflate
HTTP_X_FORWARDED_FOR 128.1.1.100, 200.244.71.6, unknown
HTTP_CACHE_CONTROL max-age=259200

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 69 de 93

Above is a table of all the cool things you have access to via the Request.ServerVariables collection. Now, I
know what you're thinking: "What do server variables have to do with any of this information?" Well, I don't
know, but what I do know is that all of the HTTP header information that is sent by the client's browser to
your server is available via this collection. You did catch that part about the client's browser....yes folks, some
of these variables are browser specific! Luckily most of them are pretty well standardized. Just don't go using
something like "HTTP_UA_PIXELS" and you'll be fine (It only works in old versions of IE!).

Look at all the info we can get! You'll notice some of these are empty. Many of them only contain data in
certain situations. For instance, all the variables that start with "CERT_" have to do with authentication
certificates. Since we aren't using any on this site, these fields are naturally blank. The same goes for the
"HTTPS_" and "AUTH_" groups of variables.

One other thing to note is that this script display all of the variables that currently exist. So, if you fire up a
browser different from the one you're using now, you may gain and/or lose some of the variables listed above.
In other words, this isn't a comprehensive list of all possible server variables, it's simply a list of the ones that
the combination of your browser and our server makes available.

ASP Source Code:

<%
Dim Item
%>

<!-- Show greeting using selected server variables -->


Hello visitor from <%= Request.ServerVariables("REMOTE_ADDR") %>! Your
browser identifies itself as <%=
Request.ServerVariables("HTTP_USER_AGENT") %>.

<BR>
<BR>

<!-- Show all server variables -->


<TABLE BORDER=2>
<TR>
<TD><B>Server Variable</B></TD>
<TD><B>Value</B></TD>
</TR>
<% For Each Item In Request.ServerVariables %>
<TR>
<TD><FONT SIZE="-1"><%= Item %></FONT></TD>
<TD><FONT SIZE="-1"><%= Request.ServerVariables(Item)
%>&nbsp;</FONT></TD>
</TR>
<% Next %>
</TABLE>

<% ' That's It! Another cool time when a few lines of code go a long
way! %>;

Sample HTML Code generated by the ASP:

<!-- Show greeting using selected server variables -->


Hello visitor from 111.111.111.2! Your
browser identifies itself as Mozilla/4.04 [en] (WinNT; I ;Nav).

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 70 de 93

<BR>
<BR>

<!-- Show all server variables -->


<TABLE BORDER=2>
<TR>
<TD><B>Server Variable</B></TD>
<TD><B>Value</B></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">ALL_HTTP</FONT></TD>
<TD><FONT SIZE="-1">HTTP_ACCEPT:image/gif, image/x-xbitmap,
image/jpeg, image/pjpeg, image/png, */*
HTTP_ACCEPT_LANGUAGE:en
HTTP_CONNECTION:Keep-Alive
HTTP_HOST:server
HTTP_USER_AGENT:Mozilla/4.04 [en] (WinNT; I ;Nav)
HTTP_COOKIE:ASPSESSIONIDQQGQQGUU=EKOJFCBDNMJJMFNGEFBMLCBI
HTTP_ACCEPT_CHARSET:iso-8859-1,*,utf-8
&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">ALL_RAW</FONT></TD>
<TD><FONT SIZE="-1">Accept: image/gif, image/x-xbitmap, image/jpeg,
image/pjpeg, image/png, */*
Accept-Language: en
Connection: Keep-Alive
Host: server
User-Agent: Mozilla/4.04 [en] (WinNT; I ;Nav)
Cookie: ASPSESSIONIDQQGQQGUU=EKOJFCBDNMJJMFNGEFBMLCBI
Accept-Charset: iso-8859-1,*,utf-8
&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">APPL_MD_PATH</FONT></TD>
<TD><FONT SIZE="-1">/LM/W3SVC/1/Root/asp101&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">APPL_PHYSICAL_PATH</FONT></TD>
<TD><FONT SIZE="-1">C:\Inetpub\wwwroot\asp101&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">AUTH_PASSWORD</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">AUTH_TYPE</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 71 de 93

<TD><FONT SIZE="-1">AUTH_USER</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">CERT_COOKIE</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">CERT_FLAGS</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">CERT_ISSUER</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">CERT_KEYSIZE</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">CERT_SECRETKEYSIZE</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">CERT_SERIALNUMBER</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">CERT_SERVER_ISSUER</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">CERT_SERVER_SUBJECT</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">CERT_SUBJECT</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">CONTENT_LENGTH</FONT></TD>
<TD><FONT SIZE="-1">0&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">CONTENT_TYPE</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 72 de 93

</TR>

<TR>
<TD><FONT SIZE="-1">GATEWAY_INTERFACE</FONT></TD>
<TD><FONT SIZE="-1">CGI/1.1&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">HTTPS</FONT></TD>
<TD><FONT SIZE="-1">off&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">HTTPS_KEYSIZE</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">HTTPS_SECRETKEYSIZE</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">HTTPS_SERVER_ISSUER</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">HTTPS_SERVER_SUBJECT</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">INSTANCE_ID</FONT></TD>
<TD><FONT SIZE="-1">1&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">INSTANCE_META_PATH</FONT></TD>
<TD><FONT SIZE="-1">/LM/W3SVC/1&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">LOCAL_ADDR</FONT></TD>
<TD><FONT SIZE="-1">111.111.111.11&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">LOGON_USER</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">PATH_INFO</FONT></TD>
<TD><FONT SIZE="-1">/asp101/samples/test.asp&nbsp;</FONT></TD>
</TR>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 73 de 93

<TR>
<TD><FONT SIZE="-1">PATH_TRANSLATED</FONT></TD>
<TD><FONT SIZE="-
1">C:\Inetpub\wwwroot\asp101\samples\test.asp&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">QUERY_STRING</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">REMOTE_ADDR</FONT></TD>
<TD><FONT SIZE="-1">111.111.111.2&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">REMOTE_HOST</FONT></TD>
<TD><FONT SIZE="-1">111.111.111.2&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">REMOTE_USER</FONT></TD>
<TD><FONT SIZE="-1">&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">REQUEST_METHOD</FONT></TD>
<TD><FONT SIZE="-1">GET&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">SCRIPT_NAME</FONT></TD>
<TD><FONT SIZE="-1">/asp101/samples/test.asp&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">SERVER_NAME</FONT></TD>
<TD><FONT SIZE="-1">server&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">SERVER_PORT</FONT></TD>
<TD><FONT SIZE="-1">80&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">SERVER_PORT_SECURE</FONT></TD>
<TD><FONT SIZE="-1">0&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">SERVER_PROTOCOL</FONT></TD>
<TD><FONT SIZE="-1">HTTP/1.0&nbsp;</FONT></TD>
</TR>

<TR>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 74 de 93

<TD><FONT SIZE="-1">SERVER_SOFTWARE</FONT></TD>
<TD><FONT SIZE="-1">Microsoft-IIS/4.0&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">URL</FONT></TD>
<TD><FONT SIZE="-1">/asp101/samples/test.asp&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">HTTP_ACCEPT</FONT></TD>
<TD><FONT SIZE="-1">image/gif, image/x-xbitmap, image/jpeg,
image/pjpeg, image/png, */*&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">HTTP_ACCEPT_LANGUAGE</FONT></TD>
<TD><FONT SIZE="-1">en&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">HTTP_CONNECTION</FONT></TD>
<TD><FONT SIZE="-1">Keep-Alive&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">HTTP_HOST</FONT></TD>
<TD><FONT SIZE="-1">server&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">HTTP_USER_AGENT</FONT></TD>
<TD><FONT SIZE="-1">Mozilla/4.04 [en] (WinNT; I
;Nav)&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">HTTP_COOKIE</FONT></TD>
<TD><FONT SIZE="-
1">ASPSESSIONIDQQGQQGUU=EKOJFCBDNMJJMFNGEFBMLCBI&nbsp;</FONT></TD>
</TR>

<TR>
<TD><FONT SIZE="-1">HTTP_ACCEPT_CHARSET</FONT></TD>
<TD><FONT SIZE="-1">iso-8859-1,*,utf-8&nbsp;</FONT></TD>
</TR>

</TABLE>

Script Output:

Access Denied!
Login:
Password:

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 75 de 93

Login Reset

Hint: Both the login and password are 'Guest'. Note that they are CaSe SeNSiTiVe!

So you're running your web site and all of a sudden you think 'Hey, what if we had an area that only certain
people could get into....now that would be cool!' So how do you do it?

Well that's a debate that has plagued many a newsgroup and web site, so we're not really gonna get too far
into that, but if you just wanna keep the pesky people out and let the people who need access in, here's a quick
and flexible solution that will work wonders!

Please note that this is exactly that....a quick and relatively simple login and password check. It isn't as secure
as SSL. It doesn't come close to using NT challenge and response. Heck, it's not even as secure as plain text
NT password validation. But here's what it does get you. You get a simple login and password check that can
pull it's validation from any source you can access (hint! hint!) from ASP. It prevents you from giving out
unnecessary NT domain passwords (generally a good idea since the log on locally right is required by users of
the web server for some unknown reason!). It also doesn't tie you up for hours writing an authentication filter
that by the time you get written you decide needs more features (you did get it finished, right?). And finally,
it's simple enough for us here at ASP101 to figure out.

A few more words of warning. While no security system is perfect, this method depends entirely upon your
coding being sound in order for it to work at all. The check needs to be in each file you want to protect which
means two things. First, you can only protect ASP pages. Secondly, you'll probably want to use a server side
include (similar to the one below) at the very top of every page to ensure consistency. This sample assumes
you stored site access levels in a session variable when the user logged in. The actual variables and how you
test them will naturally be site specific.
The line in the file to be protected would look like this:
<!-- #INCLUDE FILE="./secure.asp" -->

The file included would look something like this:


--- Begin secure.asp ---
<%
If Session("ValidatedForThisPage") = FALSE Then
Response.Redirect "LoginPage.asp"
Else
Response.Write "<!-- Validated at " & Now() & " -->"
End If
%>
--- End secure.asp ---

Note the .asp extension on the include file. We recommend this as opposed to the traditional .inc extension so
that you don't run the risk of someone directly accessing your include file and learning the implementation
details of your password system. The more someone knows about your security system, the easier it is for
them to bypass it.

You can replace the correct criteria and paths with ones applicable to your scenario. You can also display a
message instead of redirecting them to the login page. Just make sure you do a Response.End afterwards!
Using this method, you can create an include file for each set of rights you want to check. That way, if you
need to change how or what you check, it only needs to change in the include file which not only saves typing
but also stops mistakes and possible security loopholes from appearing. (That's assuming you get code right in
the include file!)

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 76 de 93

There are many different implementations of this method floating around which provide features we do not.
Our goal here, as with all our samples, has been to introduce the topic to you. We feel that if you need a
specific additional feature, it makes more sense to build upon simple code that you understand, in order to
implement it yourself, rather than to just take a 50 line script that you found somewhere and use it's features
without an understanding of what it is doing and what loopholes or drawbacks its implementation may
contain. We're not saying that everything you use, you need to have written from the ground up! What we are
saying is that, in a case like this where so little code can get the job done so well and with so little room for
error, it makes you wonder not only what all those lines of the code are doing, but also just how cleanly are
they doing it. In closing, at least take a look at what a script does before you use it! (That's especially good
advice if it's one of our scripts!)

ASP Source Code:

<%
'************************************************************************
**
' This type of script becomes more useful and managable when you are
' comparing these values to those stored in a database or some other
source
' of user information instead of hard coding them into the actual code.
' Just be sure that if a data source error arises you don't inadvertantly
' end up giving access to the pages you are trying to protect!
'************************************************************************
**

If Request.Form("login") = "Guest" AND Request.Form("password") = "Guest"


Then
Response.Write "This is all the <B>cool stuff</B> we are trying to
protect!"
Else
Response.Write "Access Denied!"
'*****************************************************************
' Note: we don't use the next line so that our description below
' the script comes in. If you wanted to just stop everything here
' you would un-comment the next line and it would stop execution.
'*****************************************************************
'Response.End
End If
%>

<FORM ACTION="login.asp" METHOD="post">


<TABLE BORDER=0>
<TR>
<TD ALIGN="right">Login:</TD>
<TD><INPUT TYPE="text" NAME="login"></INPUT></TD>
</TR>
<TR>
<TD ALIGN="right">Password:</TD>
<TD><INPUT TYPE="password" NAME="password"></INPUT></TD>
</TR>
<TR>
<TD ALIGN="right"></TD>
<TD><INPUT TYPE="submit" VALUE="Login"></INPUT>
<INPUT TYPE="reset" VALUE="Reset"></INPUT>
</TD>
</TR>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 77 de 93

</TABLE>
</FORM>
Hint: Both the login and password are 'Guest'. Note that they are CaSe
SeNSiTiVe!<BR>

Sample HTML Code generated by the ASP:

Access Denied!

Script Output:

Countdown to 2000!
There are 4 months left till the year 2000!
There are 106 days left till the year 2000!
There are 2532 hours left till the year 2000!
There are 151880 minutes left till the year 2000!
There are 9112777 seconds left till the year 2000!

If you are curious it is currently 12:40:23 PM on 9/17/99.

ASP Source Code:

<B>Countdown to 2000!</B><BR>
There are <%= DateDiff("m", Now(), CDate("01/01/2000 00:00:00")) %>
months left till the year 2000!<BR>
There are <%= DateDiff("d", Now(), CDate("01/01/2000 00:00:00")) %> days
left till the year 2000!<BR>
There are <%= DateDiff("h", Now(), CDate("01/01/2000 00:00:00")) %> hours
left till the year 2000!<BR>
There are <%= DateDiff("n", Now(), CDate("01/01/2000 00:00:00")) %>
minutes left till the year 2000!<BR>
There are <%= DateDiff("s", Now(), CDate("01/01/2000 00:00:00")) %>
seconds left till the year 2000!<BR>

<BR>
If you are curious it is currently <%= Time() %> on <%= Date() %>.<BR>

Sample HTML Code generated by the ASP:

<B>Countdown to 2000!</B><BR>
There are 18 months left till the year 2000!<BR>
There are 521 days left till the year 2000!<BR>
There are 12490 hours left till the year 2000!<BR>
There are 749378 minutes left till the year 2000!<BR>
There are 44962643 seconds left till the year 2000!<BR>

<BR>
If you are curious it is currently 2:22:37 PM on 7/29/98.<BR>

Script Output:

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 78 de 93

Tables
Table Name
Contributors
Pledges
Salesmen

Back to the Table List

Ok, here's yet another DB sample since that's what everyone seems to want. If you look through this script,
you'll see that there are no DB specific commands. This somewhat limits what you can do with it; however,
what it does allow, is for this script to work with any DB for which you can set up a DSN or provide a
connection string for!!!

That's right boys and girls, this script will work with your DB! All you need to do is set the three constants for
the connection string, username, and password, and it's up and running. (If you're using Access, you don't
even need to change the username or password unless you've password protected the database!)

I was initially even going to let you choose one or type in your own SQL server address and connection info,
but I figured that could very quickly cause problems so I've hard-coded this to our standard sample db.

Here's a quick run down of what it does. When first called it lists the tables in the DB. You select one and it
pulls in ALL THE DATA! (So don't use this on your SQL server, 5gig, inventory DB!) From there, you can
sort by any column or drill down based on any value. For instance, you connect it to your web server's log file
database and you want to see all the hits to a specific page. You simply find an instance of that page and click
on it. The script will return all records with a matching value in that field. Even once you're at this stage, you
can still sort by any field using the (+/-) in the column heading.

You can't edit anything, but for taking a quick look to see what's up, it sure beats loading up your DB tool, and
you can do it from anywhere you can get to a browser. Once again though, be VERY careful of using it on
large DB's. It was meant as a quick sample, so it doesn't warn you if you try and open a table with thousands
or even millions of lines. If you've got that kind of data, write your own script or at least put in a maximum
number of returned records.

The only other issue you may have with it is its use of ADO constants. You'll need to dig out your adovbs.inc
file. For more info see the comments near the include command.

For the best illustration of the usefulness of this script, play with the Contributors or Pledges sample tables.
The Salesmen table is more for the other DB samples and doesn't contain enough data to really try any of the
features which this script offers.
ASP Source Code:

<!--
The following include file contains all the VB ADO Constants.
If you don't want to include the whole file, you can replace all
constants with their numerical equivalents and the script will work the
same way. You could also cut and paste just the declarations you use.
We simply got tired of looking up constants since we use so many!
The file is included with VBScript so you should have it somewhere.
If you can't find it, the full path so you can download the file is

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 79 de 93

http://www.asp101.com/samples/adovbs.inc
-->
<!-- #INCLUDE FILE="./adovbs.inc" -->
<%
' BEGIN USER CONSTANTS
' To just use a DSN, the format is shown on the next line:
'Const DSN_NAME = "DSN=ASP101email"

' Two other samples I used it with. Left in as syntax examples for DSN-
less connections
'Const DSN_NAME =
"DBQ=C:\InetPub\wwwroot\asp101\samples\database.mdb;Driver={Microsoft
Access Driver (*.mdb)};DriverId=25"
'Const DSN_NAME =
"DBQ=C:\InetPub\database\donations.mdb;Driver={Microsoft Access Driver
(*.mdb)};DriverId=25"

Dim DSN_NAME
DSN_NAME = "DBQ=" & Server.MapPath("db_dsn.mdb") & ";Driver={Microsoft
Access Driver (*.mdb)};DriverId=25;"
Const DSN_USER = "username"
Const DSN_PASS = "password"
' Ok, I know these are poorly named constants, so sue me!
' This script can be used without actually setting up a DSN, so
' DSN_NAME as well as the other two constants should really be named
' something more generic like CONNECTION_STRING, CONNECTION_USER, and
' CONNECTION_PASS, but I did it this way without really thinking about
' it and I'm too lazy to change it now. If it bothers you, you do it!
' END USER CONSTANTS

' BEGIN SUBS & FUNCTIONS SECTION


Sub OpenConnection
Set objDC = Server.CreateObject("ADODB.Connection")
objDC.ConnectionTimeout = 15
objDC.CommandTimeout = 30
objDC.Open DSN_NAME, DSN_USER, DSN_PASS
End Sub

Sub OpenRecordset(sType)
Dim sSqlString ' as String - building area for SQL query
Dim sCritOperator ' as String - basically "=" or "LIKE"
Dim sCritDelimiter ' as String - parameter delimiter "", "'", or
"#"

Set objRS = Server.CreateObject("ADODB.Recordset")


Select Case sType
Case "ListTables" ' Open RS of the Tables in the DB
Set objRS = objDC.OpenSchema(adSchemaTables)
Case "ViewTable" ' Open the Selected Table
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open "[" & sTableName & "]", objDC,
adOpenForwardOnly, adLockReadOnly
Case "DrillDown" ' Open the Recordset built by the
selected options
Set objRS = Server.CreateObject("ADODB.Recordset")

' Build Our SQL Statement

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 80 de 93

sSqlString = "SELECT * FROM [" & sTableName & "]"

' If we're limiting records returned - insert the


WHERE Clause into the SQL
If sCritField <> "" Then
' Figure out if we're dealinh with Numeric,
Date, or String Values
Select Case iCritDataType
Case adSmallInt, adInteger,
adSingle, adDouble, adDecimal, adTinyInt, adUnsignedTinyInt,
adUnsignedSmallInt, adUnsignedInt, adBigInt, adUnsignedBigInt, adBinary,
adNumeric, adVarBinary, adLongVarBinary, adCurrency, adBoolean
sCritOperator = "="
sCritDelimiter = ""
Case adDate, adDBDate, adDBTime,
adDBTimeStamp
sCritOperator = "="
sCritDelimiter = "#"
Case adBSTR, adChar, adWChar,
adVarChar, adLongVarChar, adVarWChar, adLongVarWChar
sCritOperator = "LIKE"
sCritDelimiter = "'"
End Select
sSqlString = sSqlString & " WHERE [" &
sCritField & "] " & sCritOperator & " " & sCritDelimiter & sCritValue &
sCritDelimiter
End If

' If we're sorting - insert the ORDER BY clause


If sSortOrder <> "none" Then
sSqlString = sSqlString & " ORDER BY [" &
sSortField & "] " & sSortOrder
End If

sSqlString = sSqlString & ";"

' Open the actual Recordset using a Forward Only


Cursor in Read Only Mode
objRS.Open sSqlString, objDC, adOpenForwardOnly,
adLockReadOnly
End Select
End Sub

Sub CloseRecordset
objRS.Close
Set objRS = Nothing
End Sub

Sub CloseConnection
objDC.Close
Set objDC = Nothing
End Sub

Sub WriteTitle(sTitle)
Response.Write "<H2>" & sTitle & "</H2>" & vbCrLf
End Sub

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 81 de 93

Sub WriteTableHeader
Response.Write "<TABLE BORDER=1>" & vbCrLf
End Sub

Sub WriteTableRowOpen
Response.Write "<TR>" & vbCrLf
End Sub

Sub WriteTableCell(bCellIsTitle, sContents)


Response.Write vbTab & "<TD>"
If bCellIsTitle Then Response.Write "<B>"
Response.Write sContents
If bCellIsTitle Then Response.Write "</B>"
Response.Write "</TD>" & vbCrLf
End Sub

Sub WriteTableRowClose
Response.Write "</TR>" & vbCrLf
End Sub

Sub WriteTableFooter
Response.Write "</TABLE>" & vbCrLf
End Sub
' END SUBS & FUNCTIONS SECTION

' BEGIN RUNTIME CODE


' Before I start with the run-time code, let me clear up a few things.
' I've tried (and succeeded I think!) to keep all the actual HTML
' formatting contained within Subs. Hence things should be relatively
' consistent as well as being easy to change if you say want a larger
' border or perhaps a table background color or whatever...
' This, along with my attempts to try and keep my sanity, have resulted
' in a rather large proportion of Sub/Function Calls to actual code.
' Since I'm sure this is probably confusing to many newcomers to ASP
' and/or VB, I've attempted to preface each call with the optional
' Call command. Also any SUB or FUNCTION whose name starts with the
' word "Write" is basically just an encapsulation of some variation of
' a Response.Write command, while the remainder of the name represents
' whatever it happens to write.
' IE. WriteTableRowClose writes the tags used to end (or close) a
table row
' The actual HTML is (as usual) pretty vanilla flavored. If you want
' rocky-road or mint ting-a-ling (a marvelous piece of ice cream
' craftsmanship I might add), you'll need to edit the Write functions.
' Just be aware of the fact that any change to a SUB will affect ALL
' uses of it, so check the code before you try and make a change to
' just one cell and end up changing them all!
'
' Okay enough of my rambling......Onwards to the Code!!!

Dim objDC, objRS ' DataConnection and RecordSet


Dim I ' As Integer - Standard Looping Var
Dim strTemp ' As String - Temporary area for building long strings

Dim sAction ' As String - Action String to choose what to do


Dim sTableName ' As String - ...so we know what to do it to

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 82 de 93

Dim sSortField ' As String - Field to sort by


Dim sSortOrder ' As String - ...ASC or DESC
Dim sCritField ' As String - Field for DrillDown
Dim sCritValue ' As String - ...Value to compare to
Dim iCritDataType ' As Integer - so we know how to compare
' Note to all you programmers out there!
' IE4 broke this code when my QueryString was named parameter because
' it was converting the &para to the Paragraph sign even though it was
' in the middle of a word and there was no trailing ;. It works great
' in Netscape. Here's another case where IE's efforts to make things
' foolproof ruined the asp code!

' Get all the parameters we'll need


sAction = Request.QueryString("action")
If sAction = "" Then sAction = "ListTables"

sTableName = Request.QueryString("tablename")

sSortField = Request.QueryString("sf")
Select Case LCase(Request.QueryString("so"))
Case "asc"
sSortOrder = "ASC"
Case "desc"
sSortOrder = "DESC"
Case Else
sSortOrder = "none"
End Select

sCritField = Request.QueryString("cf")
If Len(sCritField) = 0 Then sCritField = ""
sCritValue = Request.QueryString("cv")
iCritDataType = Request.QueryString("cdt")
If Len(iCritDataType) <> 0 And IsNumeric(iCritDataType) Then
iCritDataType = CInt(iCritDataType)

' Start the actual DB work

' Code common to all choices.


Call OpenConnection
Call OpenRecordset(sAction)

Select Case sAction


Case "ShowDataConnectionProperties" ' Cool to look at but not
really part of the sample!
' Fake it out so we don't have problems closing the DB
OpenRecordset("ListTables")
' Get all the DataConn Properties
For I = 0 to objDC.Properties.Count - 1
Response.Write I & " " & objDC.Properties(i).Name
& ": " & objDC.Properties(I) & "<BR>" & vbCrLf
Next 'I
Case "ListTables"
Call WriteTitle("Tables")

If Not objRS.EOF Then objRS.MoveFirst


Call WriteTableHeader

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 83 de 93

Call WriteTableRowOpen
Call WriteTableCell(True, "Table Name")
Call WriteTableRowClose

Do While Not objRS.EOF


If objRS.Fields("TABLE_TYPE") = "TABLE" Then
Call WriteTableRowOpen
Call WriteTableCell(False, "<A
HREF=""./db_dsn.asp?action=ViewTable&tablename=" &
Server.URLEncode(objRS.Fields("TABLE_NAME")) & """>" &
objRS.Fields("TABLE_NAME") & "</A>")
Call WriteTableRowClose
End If
objRS.MoveNext
Loop
Call WriteTableFooter
Case "ViewTable", "DrillDown" ' The same here but in the
OpenRecordset SUB they're very different.
Call WriteTitle(sTableName)

If Not objRS.EOF Then objRS.MoveFirst


Call WriteTableHeader

Call WriteTableRowOpen
For I = 0 to objRS.Fields.Count - 1
' Build heading - the "sort by" links
' Was all on the line WriteTableCell line but I
split it up for readability
' Field name for the heading
strTemp = objRS.Fields(I).Name
' Begin Anchor for the + Sign
strTemp = strTemp & " (<A
HREF=""./db_dsn.asp"
' Set action
strTemp = strTemp & "?action=DrillDown"
' Set table name to current table
strTemp = strTemp & "&tablename=" &
Server.URLEncode(sTableName)
' Set criteria field to whatever it
currently is
strTemp = strTemp & "&cf=" &
Server.URLEncode(sCritField)
' Set criteria value to whatever it
currently is
strTemp = strTemp & "&cv=" &
Server.URLEncode(sCritValue)
' Set criteria data type to this fields'
data type
strTemp = strTemp & "&cdt=" & iCritDataType
' Set sort field to this field
strTemp = strTemp & "&sf=" &
Server.URLEncode(objRS.Fields(I).Name)
' Set sort order to this ascending (hence
the +)
strTemp = strTemp & "&so=asc"">+</A>"
' End Anchor for the + Sign

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 84 de 93

' Begin Anchor for the - Sign


' Next 8 lines are basically the same as
above except for the sort order (so)
strTemp = strTemp & "/<A
HREF=""./db_dsn.asp"
strTemp = strTemp & "?action=DrillDown"
strTemp = strTemp & "&tablename=" &
Server.URLEncode(sTableName)
strTemp = strTemp & "&cf=" &
Server.URLEncode(sCritField)
strTemp = strTemp & "&cv=" &
Server.URLEncode(sCritValue)
strTemp = strTemp & "&cdt=" & iCritDataType
strTemp = strTemp & "&sf=" &
Server.URLEncode(objRS.Fields(I).Name)
strTemp = strTemp & "&so=desc"">-</A>)"
' End Anchor for the - Sign

Call WriteTableCell(True, strTemp)


Next 'I
Call WriteTableRowClose

Do While Not objRS.EOF


Call WriteTableRowOpen
For I = 0 to objRS.Fields.Count - 1
If IsNull(objRS.Fields(I).Value) Or
objRS.Fields(I).Value = "" Or VarType(objRS.Fields(I).Value)= vbNull Then
strTemp = "&nbsp;"
Else
' These set the drill down values
which get passed if you click on any value
strTemp = "<A HREF=""./db_dsn.asp"
strTemp = strTemp & "?
action=DrillDown"
strTemp = strTemp & "&tablename=" &
Server.URLEncode(sTableName)
strTemp = strTemp & "&cf=" &
Server.URLEncode(objRS.Fields(I).Name)
strTemp = strTemp & "&cv=" &
Server.URLEncode(objRS.Fields(I).Value)
strTemp = strTemp & "&cdt=" &
objRS.Fields(I).Type
strTemp = strTemp & "&sf=" &
Server.URLEncode(sSortField)
strTemp = strTemp & "&so=" &
sSortOrder & """>"
strTemp = strTemp &
objRS.Fields(I).Value
strTemp = strTemp & "</A>"
End If
Call WriteTableCell(False, strTemp)
Next 'I
Call WriteTableRowClose
objRS.MoveNext
Loop
Call WriteTableFooter
End Select

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 85 de 93

' Close Data Access Objects and free DB variables


Call CloseRecordset
Call CloseConnection
' END RUNTIME CODE
%>
<BR>
<A HREF="./db_dsn.asp">Back to the Table List</A>

Sample HTML Code generated by the ASP:

<!--
The following include file contains all the VB ADO Constants.
If you don't want to include the whole file, you can replace all
constants with their numerical equivalents and the script will work the
same way. You could also cut and paste just the declarations you use.
We simply got tired of looking up constants since we use so many!
The file is included with VBScript so you should have it somewhere.
If you can't find it, the full path so you can download the file is
http://www.asp101.com/samples/adovbs.inc
-->
<H2>Pledges</H2>
<TABLE BORDER=1>
<TR>
<TD><B>PledgeID (<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Pledg
eID&so=asc">+</A>/<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Pledg
eID&so=desc">-</A>)</B></TD>
<TD><B>ContributorID (<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Contr
ibutorID&so=asc">+</A>/<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Contr
ibutorID&so=desc">-</A>)</B></TD>
<TD><B>DatePledged (<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=DateP
ledged&so=asc">+</A>/<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=DateP
ledged&so=desc">-</A>)</B></TD>
<TD><B>AmountPledged (<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Amoun
tPledged&so=asc">+</A>/<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Amoun
tPledged&so=desc">-</A>)</B></TD>
<TD><B>Paid (<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Paid&
so=asc">+</A>/<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Paid&
so=desc">-</A>)</B></TD>
<TD><B>PaymentDate (<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Payme
ntDate&so=asc">+</A>/<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Payme
ntDate&so=desc">-</A>)</B></TD>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 86 de 93

<TD><B>CardholdersName (<A HREF="./db_dsn.asp?


action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Cardh
oldersName&so=asc">+</A>/<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Cardh
oldersName&so=desc">-</A>)</B></TD>
<TD><B>CreditCardNumber (<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Credi
tCardNumber&so=asc">+</A>/<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Credi
tCardNumber&so=desc">-</A>)</B></TD>
<TD><B>CreditCardExpDate (<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Credi
tCardExpDate&so=asc">+</A>/<A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=Credi
tCardExpDate&so=desc">-</A>)</B></TD>
</TR>
<TR>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=PledgeID&cv=2&cdt=3&sf=DatePledged&
so=ASC">2</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=ContributorID&cv=1&cdt=3&sf=DatePle
dged&so=ASC">1</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=DatePledged&cv=2%2F1%2F95&cdt=135&s
f=DatePledged&so=ASC">2/1/95</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=DateP
ledged&so=ASC">100</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=Paid&cv=True&cdt=11&sf=DatePledged&
so=ASC">True</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=PaymentDate&cv=2%2F2%2F95&cdt=135&s
f=DatePledged&so=ASC">2/2/95</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CardholdersName&cv=John+Steel&cdt=2
00&sf=DatePledged&so=ASC">John Steel</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CreditCardNumber&cv=238742963432427
5&cdt=200&sf=DatePledged&so=ASC">2387429634324275</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CreditCardExpDate&cv=10%2F1%2F96&cd
t=135&sf=DatePledged&so=ASC">10/1/96</A></TD>
</TR>
<TR>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=PledgeID&cv=5&cdt=3&sf=DatePledged&
so=ASC">5</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=ContributorID&cv=1&cdt=3&sf=DatePle
dged&so=ASC">1</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=DatePledged&cv=2%2F22%2F95&cdt=135&
sf=DatePledged&so=ASC">2/22/95</A></TD>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 87 de 93

<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=DateP
ledged&so=ASC">100</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=Paid&cv=True&cdt=11&sf=DatePledged&
so=ASC">True</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=PaymentDate&cv=2%2F25%2F95&cdt=135&
sf=DatePledged&so=ASC">2/25/95</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CardholdersName&cv=John+Steel&cdt=2
00&sf=DatePledged&so=ASC">John Steel</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CreditCardNumber&cv=238742963432427
5&cdt=200&sf=DatePledged&so=ASC">2387429634324275</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CreditCardExpDate&cv=10%2F1%2F96&cd
t=135&sf=DatePledged&so=ASC">10/1/96</A></TD>
</TR>
<TR>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=PledgeID&cv=19&cdt=3&sf=DatePledged
&so=ASC">19</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=ContributorID&cv=4&cdt=3&sf=DatePle
dged&so=ASC">4</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=DatePledged&cv=5%2F14%2F95&cdt=135&
sf=DatePledged&so=ASC">5/14/95</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=DateP
ledged&so=ASC">100</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=Paid&cv=True&cdt=11&sf=DatePledged&
so=ASC">True</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=PaymentDate&cv=5%2F22%2F95&cdt=135&
sf=DatePledged&so=ASC">5/22/95</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CardholdersName&cv=Art+Braunschweig
er&cdt=200&sf=DatePledged&so=ASC">Art Braunschweiger</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CreditCardNumber&cv=345739408751714
8&cdt=200&sf=DatePledged&so=ASC">3457394087517148</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CreditCardExpDate&cv=11%2F1%2F96&cd
t=135&sf=DatePledged&so=ASC">11/1/96</A></TD>
</TR>
<TR>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=PledgeID&cv=17&cdt=3&sf=DatePledged
&so=ASC">17</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=ContributorID&cv=4&cdt=3&sf=DatePle
dged&so=ASC">4</A></TD>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 88 de 93

<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=DatePledged&cv=5%2F22%2F95&cdt=135&
sf=DatePledged&so=ASC">5/22/95</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=DateP
ledged&so=ASC">100</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=Paid&cv=True&cdt=11&sf=DatePledged&
so=ASC">True</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=PaymentDate&cv=5%2F27%2F95&cdt=135&
sf=DatePledged&so=ASC">5/27/95</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CardholdersName&cv=Art+Braunschweig
er&cdt=200&sf=DatePledged&so=ASC">Art Braunschweiger</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CreditCardNumber&cv=345739408751714
8&cdt=200&sf=DatePledged&so=ASC">3457394087517148</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CreditCardExpDate&cv=11%2F1%2F96&cd
t=135&sf=DatePledged&so=ASC">11/1/96</A></TD>
</TR>
<TR>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=PledgeID&cv=24&cdt=3&sf=DatePledged
&so=ASC">24</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=ContributorID&cv=5&cdt=3&sf=DatePle
dged&so=ASC">5</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=DatePledged&cv=6%2F22%2F95&cdt=135&
sf=DatePledged&so=ASC">6/22/95</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=AmountPledged&cv=100&cdt=6&sf=DateP
ledged&so=ASC">100</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=Paid&cv=True&cdt=11&sf=DatePledged&
so=ASC">True</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=PaymentDate&cv=6%2F30%2F95&cdt=135&
sf=DatePledged&so=ASC">6/30/95</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CardholdersName&cv=Fran+Wilson&cdt=
200&sf=DatePledged&so=ASC">Fran Wilson</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CreditCardNumber&cv=237964046895336
7&cdt=200&sf=DatePledged&so=ASC">2379640468953367</A></TD>
<TD><A HREF="./db_dsn.asp?
action=DrillDown&tablename=Pledges&cf=CreditCardExpDate&cv=4%2F1%2F96&cdt
=135&sf=DatePledged&so=ASC">4/1/96</A></TD>
</TR>
</TABLE>

<BR>
<A HREF="./db_dsn.asp">Back to the Table List</A>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 89 de 93

Script Output:

This text is in the file "textfile.txt"!


It was written by a visitor to ASP 101 on 9/17/99 at 12:46:12 PM.

Write to the text file

This script reads the text from a file on our server and displays it on the page. In order to do it's job it uses the
FileSystemObject included with IIS3 and IIS4. If you run this on your server, please be aware that in it's
current state it does require the file to exist. The above link runs a script that will create the text file this script
reads from!
ASP Source Code:

<%
' Declare variables for the File System Object and the File to be
accessed.
Dim objFSO, objTextFile

' Create an instance of the the File System Object and assign it to
objFSO.
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Open the file


'Set objTextFile =
objFSO.OpenTextFile("C:\InetPub\PR86027\samples\textfile.txt")
Set objTextFile = objFSO.OpenTextFile(Server.MapPath("textfile.txt"))

Do While Not objTextFile.AtEndOfStream


Response.Write objTextFile.ReadLine & "<BR>" & vbCrLf
Loop

' Close the file.


objTextFile.Close

' Release reference to the text file.


Set objTextFile = Nothing

' Release reference to the File System Object.


Set objFSO = Nothing
%>

<BR>

<A HREF="./textfile_w.asp">Write to the text file</A><BR>

Sample HTML Code generated by the ASP:

This text is in the file "textfile.txt"!<BR>


It was written by a visitor to ASP101 on 7/31/98 at 3:01:29 PM.<BR>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 90 de 93

Script Output:

Writing to file "textfile.txt".


Writing line 1.... done!
Writing line 2.... done!
Finished!

Read from the text file.

This script writes the text to the file on our server that the previous page reads from. Again, in order to
accomplish this it creates an instance of the FileSystemObject. It then uses this object to write text to the
specified file. Just so there's something to see, the script outputs messages to the browser as it proceeds.
Please note that these aren't needed for the script to function
ASP Source Code:

<%
' Declare variables for the File System Object and the File to be
accessed.
Dim objFSO, objTextFile

' Create an instance of the the File System Object and assign it to
objFSO.
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Open the file


'Set objTextFile =
objFSO.CreateTextFile("C:\InetPub\PR86027\samples\textfile.txt")
Set objTextFile = objFSO.CreateTextFile(Server.MapPath("textfile.txt"))
%>

Writing to file "textfile.txt".<BR>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Writing line 1....


<% objTextFile.WriteLine "This text is in the file ""textfile.txt""!" %>
done!<BR>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Writing line 2....


<% objTextFile.WriteLine "It was written by a visitor to ASP 101 on " &
Date() & " at " & Time() & "." %>
done!<BR>

Finished!<BR>

<%
' Close the file.
objTextFile.Close

' Release reference to the text file.


Set objTextFile = Nothing

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 91 de 93

' Release reference to the File System Object.


Set objFSO = Nothing
%>

<BR>

<A HREF="./textfile.asp">Read from the text file.</A><BR>

Sample HTML Code generated by the ASP:

Writing to file "textfile.txt".<BR>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Writing line 1....

done!<BR>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Writing line 2....

done!<BR>

Finished!<BR>

Script Output:

Method 1 - Break Script:


This is some text

Method 2 - Response.Write:
This is some text

Did you ever notice that sometimes when we need to write some HTML in the middle of a script we break out
and then restart, while other times we use the Response.Write command. This sample will show you the
difference between the two different methods and discuss the benefits and downfalls of each.

Once you've looked over the sample and know the difference between the two methods, you can choose
whichever method you prefer. Keep in mind that while there are some performance issues associated with
your choice, the most important issue is to use whichever you feel most comfortable using or will make your
code easiest to follow when you need to come back to it.

ASP Source Code:

<%
Dim sSomeText
sSomeText = "This is some text"
' OK, here's the scenario:
' We're happily scripting along and all of a sudden we need to
' output the value of the variable sSomeText inside a bold tag.
' This naturally means we need to output some plain HTML for the
' beginning and end <B> tags.

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 92 de 93

' Output title - this really isn't part of the sample, but we need to
label things!
Response.Write "Method 1 - Break Script:<BR>" & vbCrLf

' *** Method 1 - Break Script ***


' We stop our scripting, drop out to the HTML that will be sent
' directly to the browser and then just type our HTML tags as we
' normally would in a plain HTML page. This is actually done
' twice in this instance. Once for the <B> and once for the </B>.
%><B><%
Response.Write sSomeText
%></B><%

' Note: in our samples we would normally format it more like this:
'
' % >
' <B>< % Response.Write sSomeText % ></B>
' < %
'
' the two are functionally equivalent, the only difference is the
' placement of the carriage returns. The first is shown to more
' clearly illustrate where we stop and resume the script each time.
'
' The main benefit of this method is it often allows you to more
' easily distinguish between script and HTML than the upcoming
' method 2. We use it most often when we have a large amount of
' HTML into which we need to place a value or two. For example, if
' you've got a table which has a lot of formatting it's easier to
' code your table as normal and simply start script, display the
' value, and end script in the table cell where the value goes.
' The < %= % > format of the Response.Write command is very handy
' in this type of scenario!
' *** End Method 1 ***

' Output some line feeds so the next sample appears on a new line:
' Speaking of which, you'll notice we use both the HTML tag <BR>
' and a vbCrLF which is a Visual Basic constant for the
' Carriage Return - Line Feed character. Here's why!
' Since HTML ignores spacing and carriage returns, we put in the
' <BR> so our next output doesn't appear on the same line as the
' previous one. Since we're inside script, the standard carriage
' returns aren't shown in the resulting HTML (which would then
' ignore them); however, since our site is designed for our
' visitors to read our code, to keep our HTML code neat for our
' readers, we add the vbCrLf. The result of the HTML when viewed
' in a browser is the same either way.
' Note: the first <BR> ends the previous line.
' the second <BR> skips a line.
Response.Write "<BR>" & vbCrLf & "<BR>" & vbCrLf

' Output title - Once again, not really part of the sample. (Ignore the
man behind the curtain!)
Response.Write "Method 2 - Response.Write:<BR>" & vbCrLf

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
ASPDica1.doc Página 93 de 93

' *** Method 2 - Response.Write ***


' In this method we never drop out of our script. We accomplish
' this by simply outputting the HTML as Strings along with the
' value of our variable.
Response.Write "<B>"
Response.Write sSomeText
Response.Write "</B><BR>"

' Note: we would normally have it all on one line like this:
'
' Response.Write "<B>" & sSomeText & "</B><BR>"
'
' Once again, the two are functionally equivalent, the only
' difference is the placement of the carriage returns. The first is
' shown to more clearly illustrate the process.

' The main benefit of this method is it lets you output a little
' HTML without breaking stride. We use it most often when we have a
' situation like this example. We've got some a variable that we
' just want to throw a quick tag around. It is also reportedly
' quicker, in terms of server processing time, since the ASP
' processor doesn't need to stop parsing and then restart when we
' start scripting again. (We've yet to be able to actually notice
' a perceivable difference, but that's what we hear!)
'
' There is also one caveat when using this method:
' BE CAREFUL USING THE " CHARACTER
' In VBScript the " is the string delimiter, hence a command like
' the following will cause problems:
' Response.Write "<A HREF="./output.asp">Output</A>"
' This WILL NOT result in <A HREF="./output.asp">Output</A> being
' sent to the browser. What it will give you is an error because
' it thinks the string ended at the " after the = sign and it doesn't
' recognize the rest of the text as a valid VBScript command.
' The syntax to achieve the desired result is:
' Response.Write "<A HREF=""./output.asp"">Output</A>"
' Notice the "" instead of " wherever we want a " in the string!
' *** End Method 2 ***
%>

Sample HTML Code generated by the ASP:

Method 1 - Break Script:<BR>


<B>This is some text</B><BR>
<BR>
Method 2 - Response.Write:<BR>
<B>This is some text</B><BR>

www.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa

Você também pode gostar