CGI en Visual Basic
CGI en Visual Basic
CGI en Visual Basic
Pgina 1 de 11
Copyright 1996, Corporacin Que . Todos los derechos reservados. Ninguna parte de este libro puede ser usada o reproducida en cualquier forma o por cualquier medio, o almacenados en un sistema de base de datos o recuperacin sin el permiso previo y por escrito del editor, excepto en el caso de citas breves en artculos crticos y revisiones. Cmo hacer copias de cualquier parte de este libro para cualquier otro fin que no sea su propio uso personal es una violacin de las leyes de copyright de Estados Unidos. Para mayor informacin, la direccin Que Corporation, 201 West 103 rd Street, Indianapolis, IN 46290 o en support @ mcp. com . Aviso: Este material es un extracto de edicin especial utilizando CGI , ISBN: 0-7897-0740-3. La versin electrnica de este material no ha pasado por la fase de prueba final de que la lectura del libro pasa por antes de ser publicado en forma impresa. Algunos errores pueden existir aqu que se corrigen antes de que el libro se publique. Este material se proporciona "tal cual" sin garanta de ningn tipo.
Lo que el CGI de Windows estndar es y cmo se diferencia del estndar (UNIX) CGI Lo que los archivos de entrada y salida de Windows CGI son y cmo son decodificados Cul es el marco cgi32.bas Cmo configurar una aplicacin para Windows con Visual Basic CGI Como crear formas Cmo procesar los datos presentados Cmo acceder a una base de datos con Visual Basic Cmo configurar una base de datos con capacidad de bsqueda Web telfono nmero
Puede descargar varios try-antes-de-comprar las versiones de los servidores web. Puede obtener el servidor Web Sitio Web, que se ejecuta bajo Windows 95 y Windows NT, desde este sitio . Usted puede incluso instalar un servidor Web en un PC que no est conectado a Internet y utilizar la direccin IP de bucle invertido para acceder a l ( http://127.0.0.1 ). Lea la documentacin que se incluye con el servidor Web en la forma de instalarlo en su sistema.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 2 de 11
La figura. 21,1 Usted puede solicitar una lnea pizza. Los contactos del usuario del navegador Web de su servidor y enva los datos que se han rellenado los campos y el camino de la aplicacin CGI que maneja la peticin. La figura 21.2 muestra lo que ocurre cuando el usuario enva los datos. La figura. 21,2 Durante una solicitud de Windows CGI, el servidor inicia una aplicacin que procesa un archivo de entrada y enva los resultados a un archivo de salida. El archivo de salida es posteriormente enviada por el servidor. Despus de todo los datos son enviados por el navegador Web del usuario, el servidor inicia la aplicacin CGI. Esto se hace utilizando la lnea de comandos siguiente sintaxis:
cgi-aplicacin cgi-data-file contenido del archivo de salida-file url-args
cgi-aplicacin
de este parmetro es la ruta completa de la aplicacin CGI que suele ser un ejecutable de Windows. En la prctica, las aplicaciones CGI estn localizados en un directorio independiente. Este directorio no es accesible desde Internet, por lo que no se puede descargar el ejecutable. Este directorio se suele fijar en la configuracin del servidor. Si su directorio de Windows CGI se establece en CGI-WIN, la ruta podra ser algo como c: \ website \ cgi-win \ order.exe. cgi-data-file Este parmetro es la ruta de acceso al archivo que contiene todos los datos relativos a la solicitud. Contiene los campos enviados por el usuario (qu tamao, la direccin del usuario, y as sucesivamente) y alguna informacin sobre la conexin (la direccin de Internet y el tipo de software de Internet del usuario, por ejemplo). Estos datos son ledos por la aplicacin CGI despus de que se puso en marcha. El archivo se coloca en el directorio temporal. contenido-file El archivo de contenido incluye todo el contenido que se present durante la solicitud del usuario. Se podra, por ejemplo, contienen un archivo que el usuario cargado. Casi nunca se utiliza por los programadores de CGI, ya que contiene datos sin procesar. Este archivo se coloca en el directorio temporal. archivo-salida Este parmetro es la ruta de acceso al archivo de salida, sino que se utiliza para pasar datos desde la aplicacin CGI en el servidor. Estos datos podran ser una confirmacin de que la orden es aceptada. El servidor enva estos datos al usuario, por lo general, est en formato HTML. url-args Este parmetro es cualquier cosa que siga a? (Signo de interrogacin) en la direccin URL solicitada por el usuario. Si no hay ningn argumento URL est presente, se omite este parmetro desde la lnea de comandos. Algunos scripts CGI base de datos de bsqueda utilizan argumentos de URL.
Entonces, qu sucede cuando el servidor inicia la aplicacin CGI? La aplicacin CGI inicializa y lee los datos desde el archivo de entrada. Dependiendo de la entrada, la aplicacin genera un archivo de salida. Supongamos que todos los campos se han llenado correctamente por el usuario y que el orden puede ser reconocido. La aplicacin CGI luego escribe fin acept el archivo de salida y salidas. Las noticias del servidor Web que la aplicacin CGI ha terminado, lee el archivo de salida, y enva los datos del archivo de salida de vuelta al usuario.
[CGI] Solicitud de protocolo HTTP/1.0 = mtodo de una peticin GET = ruta ejecutable = / Software de Servidor cgi-win/order.exe WebSite/1.0 = Nombre del servidor = server.domain.com Serv
Si usted se centra en la [CGI] seccin, un par de cosas que puede atraer su atencin: una de ellas es Request Mtodo . El usuario solicita que este mtodo sea realizado por el servidor ( GET en este caso).
Consulte "Solicitud de variables especficas del medio ambiente," para obtener ms informacin sobre los mtodos de peticin.
Como se puede ver, el archivo de entrada contiene informacin ms interesante. En el [Extra Headers] seccin, puede detectar el tipo de navegador Web del usuario. El User-Agent artculo que usted dice que un navegador Netscape 2.0 se ejecuta en Windows 95 se utiliza (Mozilla es el nombre que los desarrolladores de Netscape para utilizar su navegador). La direccin IP de Internet del usuario se muestra despus de que el anfitrin material (es 123.123.123.123 en este caso). Puede utilizar todos estos datos en la aplicacin CGI. Listado 21.2 muestra otro archivo de entrada.
Listado 21.2 de archivo de entrada para un usuario de la POST Request
[CGI] Solicitud de protocolo HTTP/1.0 = Mtodo = Request ruta ejecutable = POST / Software de Servidor cgi-win/order.exe WebSite/1.0 = Nombre del servidor = server.domain.com Server Port
El archivo de entrada ahora menciona Solicitud method = post . En este caso, un usuario enva datos, como se muestra en la [Forma ] literal seccin. Como se puede ver, ha ordenado una pizza. La direccin, nmero de telfono, qu tipo de pizza-la informacin es todo lo que hay.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 3 de 11
En esta seccin, se crea la primera aplicacin CGI, lo que le permite solicitar un usuario de e-mail y enviar un formulario, mostrando que la direccin ha sido enviada correctamente. Luego, agregar ms campos y ver cmo decodificar. Se comienza con la creacin del proyecto en Visual Basic. Estoy asumiendo que usted est utilizando Visual Basic 4, la versin de 32-bit. Vase ms adelante la seccin "Obtener la ltima versin de Visual Basic" para obtener ms informacin. Las versiones anteriores de Visual Basic requiere otra versin del marco de CGI (cgi.bas, que se distribuye con el servidor Web WinHTTPD, disponible en Internet en este sitio ). La versin de 16 bits de Visual Basic 4 debera funcionar bien con cgi32.bas, pero yo le aconsejo que utilice la versin de 32-bit. (Vase ms adelante la seccin "Rendimiento del servidor" para una discusin sobre este tema). Ejecute Visual Basic y cree un nuevo proyecto con la apertura de la F ile men y eligiendo N ew. Eliminar todas las formas (en su caso) mediante la apertura de la F ile men y elegir R emove. A continuacin, eliminar todos los mdulos de una manera similar (si los hay). A continuacin, abra la T erramientas men y seleccione C ustom Controles para abrir los controles personalizados cuadro de dilogo. Asegrese de deseleccionar todo en la lista, por lo que puede disminuir el nmero de mdulos de tu proyecto necesita para cargar y aumentar significativamente el rendimiento de la aplicacin CGI. A continuacin, cierre el cuadro de dilogo Controles personalizados. A continuacin, abra la F ile men y escoja el A d d del archivo, a continuacin, aadir los archivos cgi32.bas a su proyecto. Es el marco CGI bsico y debe estar en el directorio cgi-src su servidor Web o en el directorio actual. El cdigo proporcionado aqu se prueba con la versin 1.7 de cgi32.bas pero debera funcionar con versiones ms antiguas y ms nuevas tambin.
Tenga cuidado con el archivo cgi32.bas porque usted lo utiliza en todos los proyectos. En principio, no es necesario editar este archivo. Ahora agregue un archivo de base en el que usted puede poner su propio cdigo. Abra la I nsert men y seleccione M dulo para agregar un archivo de base al proyecto. Visual Basic lo Module1 nombres para usted. Nunca se debe agregar un formulario a una aplicacin CGI, pero se apoya en la entrada y salida de archivos y no necesita abrir una ventana durante la ejecucin. Una forma se ralentizar la ejecucin de la aplicacin. Ahora est listo para crear el procedimiento que se inicia despus de la ejecucin del ejecutable CGI se ejecuta en el servidor. Este procedimiento se llama CGI_Main . Cuando ests revisando una aplicacin CGI existente, siempre hay que empezar a buscar en este procedimiento. Abra la ventana de cdigo de Module1. Asegrese de que usted est en el general-declaraciones seccin de Module1, a continuacin, crear la CGI_Main procedimiento escribiendo lo siguiente:
Sub CGI_Main
Visual Basic crea el procedimiento para usted. De la misma manera, crear un Inter_Main procedimiento en general-declaraciones seccin de Module1 escribiendo la siguiente lnea:
Sub Inter_Main
El Inter_Main rutina se utiliza slo cuando el script no se ejecuta en un servidor Web, y no utiliza esta rutina en este proyecto. Sin embargo, cgi32.bas contiene una llamada a la Inter_Main subrutina, y no se puede compilar el proyecto sin l.
Sub CGI_Main () Si CGI_RequestMethod = "GET" Entonces Final Exit Sub SendRequest If End Sub
Este cdigo resulta en la SendRequest procedimiento que se llama cuando el usuario solicita el GET mtodo. En este procedimiento, se genera un documento HTML. A continuacin, agregue el SendRequest procedimiento. En la general-declaraciones seccin de Module1, ingrese todo el cdigo mostrado en el listado 21.4. (Visual Basic crea el SendRequest procedimiento para usted despus de escribir el Sub SendRequest lnea.)
Listado 21.4 El SendRequest Procedimiento de email.bas
Sub SendRequest () Send ("Content-type: text / html") Send ("") Send ("<HTML> <HEAD> <TITLE>") Send (". Por favor, introduzca su e-mail address") Enviar ("</ TITLE> </ HEAD>") Send ("<BO
A continuacin, el contenido de la SendRequest procedimiento se discutir. Usted puede haber notado que utiliza el send () de rutina para escribir datos en el archivo de salida, esta rutina se define en el marco cgi32.bas. El SendRequest procedimiento se inicia con la siguiente lnea:
Enviar ("Content-type: text / html")
Los exploradores Web de los usuarios necesitan saber qu tipo de informacin se est enviando. En este caso, se enva HTML, pero tambin se podra enviar una imagen GIF, un archivo de sonido, un ejecutable binario, y as sucesivamente, siempre y cuando usted indica esto con el correcto tipo de contenido. Si se olvida de incluir una declaracin de tipo de contenido HTML, se genera un error. Inicio de una pgina HTML con un ttulo es una buena costumbre. El ttulo aparece en la barra de ttulo de los navegadores web de los usuarios despus de que el documento HTML se carga. El ttulo se agrega con el siguiente cdigo:
Enviar ("<HTML> <HEAD> <TITLE>") Send ("Por favor, introduzca su direccin de correo electrnico.") Send ("</ TITLE> </ HEAD>")
Para configurar un formulario en HTML que se pueden enviar a un servidor, debe especificar la FORM METHOD , que indica a los navegadores de los usuarios Web que mtodo a peticin. En este caso, los navegadores de los usuarios web realizar un POSTE peticin. Lo que es ms, se ve la accin que se realizar. Los usuarios con el servidor y le pedir que ejecute el archivo email.exe (el ejecutable CGI). Podra especificar la URL completa en el servidor, tambin, pero usted tendra que cambiar el guin cuando lo mueve a otro servidor. La forma en que se especifica la URL ahora, el navegador del usuario rellenar el resto de la URL. En este caso, se usa lo siguiente:
Enviar ("<FORM METHOD=""POST"" ACTION=""/cgi-win\email.exe"">")
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 4 de 11
Esta lnea contiene dos comillas dobles. En Visual Basic, las comillas tienen un significado especial. Si especifica dos comillas dobles, Visual Basic omite la primera y la segunda se refiere a una marca como texto sin formato cita. Por ejemplo, "METHOD =" POST "," resultados en METHOD = "POST" que se envan a los usuarios. A continuacin, cree un campo de entrada en la que los usuarios pueden rellenar sus direcciones de correo electrnico:
Enviar ("<INPUT SIZE=30 NAME=""EMailAddress"">")
El campo de entrada es de 30 caracteres de ancho y est descrita por el identificador EmailAddress . Usted puede agregar otras opciones, que se describen ms adelante. Por ahora, podemos estar satisfechos con este campo simple. Lo nico que necesitas es aadir un botn Enviar:
Enviar ("<INPUT TYPE=""submit"" VALUE=""Submit"">.")
Tenga en cuenta que este botn es otro tipo de entrada. El pie de foto poner el botn est determinado por el VALOR variable, en este caso, el ttulo est en "Enviar" . Poner fin al formulario HTML con la sintaxis correcta es una buena costumbre:
Enviar ("</ FORM>") Send ("</ BODY> </ HTML>")
Ahora puede guardar el proyecto y preparar el ejecutable CGI. Guarde el proyecto abriendo el F ile men y elegir S Proyecto de ave. Guardar Module1 (el mdulo que ha aadido al proyecto) como email.bas y al proyecto que email.vbp. Puede guardar estos archivos en un directorio independiente o en CGI-SRC directorio de su servidor. A continuacin, compile el archivo. EXE abriendo la F ile men y elegir Ma k Exe e. Nombre de la email.exe ejecutable y colocarlo en CGI-WIN directorio de su servidor o cualquier otro directorio que est habilitado para Windows CGI. Este directorio suele establecerse durante el proceso de instalacin de su servidor, pero se puede cambiar despus (consulte el manual de su servidor). Ahora, usted puede tener acceso al archivo ejecutable CGI mediante el explorador Web. Apunte su navegador web a la siguiente URL:
z
Reemplace your.servers.address con la direccin de Internet de su servidor Web, si se ejecuta el navegador web y el servidor en la misma mquina, puede utilizar el nmero de IP loopback: 127.0.0.1 . (Si su equipo no est conectado a la Red, usted necesita utilizar el nmero de IP de bucle invertido.) Asegrese de que utiliza una barra invertida (\) en el nombre de la ruta, muchos problemas surgen del uso de una barra diagonal (/) en lugar . Si todo va bien, usted termina con una forma que se muestra en la figura 21.3. La figura. 21,3 Despus de ejecutar la aplicacin email.exe con un navegador web, los resultados deben verse as. Seal mi navegador web a la secuencia de comandos CGI, pero no pasa nada. Qu est mal? No entre en pnico todava. Primero, asegrese de que el servidor Web se est ejecutando y que ha suministrado la direccin URL correcta para su servidor. Si ejecuta el servidor y el navegador Web en el mismo equipo, puede utilizar el nmero de IP de bucle invertido ( 127.0.0.1 ) como direccin IP. Eso se puede acceder a los archivos HTML normales en el servidor es una buena indicacin de que tiene la direccin IP correcta y que el servidor est funcionando correctamente. Despus de convencerse de que ha colocado el archivo email.exe en un directorio que est habilitado para Windows las aplicaciones CGI. No puede ejecutar aplicaciones CGI desde directorios estndar HTML en el servidor (por ejemplo, \ htdocs). Los archivos en los directorios HTML son ledas por el servidor, las aplicaciones CGI se ejecutan, por lo que un directorio especial necesita ser configurado para Windows archivos CGI. Por lo general, este directorio se llama \ cgiwin. Tengo la impresin de que la aplicacin se ejecuta bien, pero el servidor se queja de vaco de salida de CGI programa . Usted no puede colocar un ejecutable de Windows en un directorio CGI CGI estndar. El servidor utiliza un mtodo diferente para el lanzamiento de este tipo de aplicaciones CGI. Si un directorio est habilitada para Windows o estndar CGI se establece en la configuracin de su servidor, por lo que debe consultar el manual de su servidor en esta materia. Con la mayora de servidores web, precompilados ejecutables CGI se distribuyen. Si puede ejecutar estos archivos, hay muchas posibilidades de que algo anda mal dentro de su ejecutable CGI Windows. Si puede ejecutar otros archivos ejecutables CGI, debe comprobar si la versin de su archivo cgi32.bas es reciente. Estos scripts se han probado con la versin 1.7, pero debera, en principio, el trabajo con versiones anteriores y posteriores. De todos modos, tratando una versin ms reciente no puede doler. Las versiones recientes de cgi32.bas se distribuyen con el servidor Web Sitio Web, y se pueden obtener a travs de Internet en este sitio . La mayora de los problemas con los scripts de Visual Basic CGI surgen del hecho de que la gente utiliza los cgi.bas anticuadas en lugar de los nuevos archivos cgi32.bas en el 32-bit Visual Basic 4 ambiente. cgi.bas utiliza llamadas a la API de Windows de 16 bits, por lo que no puede compilar las aplicaciones que utilizan cgi.bas en el 32-bit VB 4 ambiente. Usted debe eliminar el archivo cgi.bas y reemplazarlo con una versin reciente del archivo cgi32.bas. Si el servidor Web se ha configurado correctamente, pero el problema radica en la aplicacin de Visual Basic CGI, es probable que reciba un mensaje de error despus de acceder a la aplicacin con el navegador Web. A continuacin, puede intentar solucionar el problema utilizando esta informacin.
A veces, los errores que se producen dentro de su programa de Visual Basic son difciles de rastrear. Debido a que la aplicacin CGI es llamado por el servidor, se ejecuta la aplicacin en el entorno de diseo de Visual Basic no es particularmente til. Usted puede agregar la siguiente lnea al inicio de la CGI_Main procedimiento:
MsgBox ("Hello World!")
Al compilar la aplicacin CGI y ejecutarlo, una pequea caja con el mensaje Hola Mundo! aparecer en la PC servidor. La aplicacin se detiene en esta lnea hasta que haga clic en Aceptar. Puede mover el MsgBox lnea a travs de la aplicacin hasta que se genera el error antes de que la caja se abrir. Con un poco de experiencia, es fcil localizar la lnea que genera el error.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 5 de 11
Ahora puede volver al entorno de diseo de Visual Basic y agregar cdigo para el POSTE mtodo de solicitud. En el mdulo de email.bas, cambiar el CGI_Main procedimiento como se muestra en negrita en el listado de 21,5.
21.5 El listado revisado CGI_Main Procedimiento de email.bas
Sub CGI_Main () Si CGI_RequestMethod = "GET" Luego Sub SendRequest salida dems sendResponse Exit Sub End If End Sub
El sendResponse procedimiento controla los Post peticiones. A continuacin, introduzca la sendResponse procedimiento como se muestra en el listado 21.6.
Listado 21.6 La sendResponse Procedimiento de email.bas
Sub sendResponse () Dim Email Email String = GetSmallField ("EmailAddress") Send ("Content-type: text / html") Send ("") Send ("! <HTML> <HEAD> Gracias <TITLE>") Enviar ("</ TITLE> </ HE
La siguiente lnea es significativo porque muestra cmo se puede leer los campos del formulario que ha sido sometido por los usuarios mediante el uso de la GetSmallField () funcin, que es parte del marco cgi32.bas:
Email = GetSmallField ("EmailAddress")
El GetSmallField () funcin se llama con el nombre del campo como argumento. Usted puede haber notado que EmailAddress es el nombre del campo de entrada que especific en el SendRequest subrutina:
Enviar ("<INPUT SIZE=30 NAME=""EMailAddress"">")
La variable -mail se enva a los usuarios despus utilizando el cdigo siguiente (tenga en cuenta que previamente se ha declarado el correo electrnico mediante el uso de una variable de Dim declaracin):
Enviar ("Hemos registrado:" Email +)
Guarde y compile el proyecto y ejecutar la aplicacin CGI apuntando el navegador web a la URL correcta como lo ha hecho antes. A continuacin, escriba algo en el campo de correo electrnico y haga clic en Enviar. Si todo va bien, se ve una respuesta como la que se muestra en la figura 21.4. A diferencia de lo que el resultado muestra, que tiene, por supuesto, no registr nada en este momento. La figura. 21,4 Cumplimentacin de una direccin de correo electrnico y haga clic en botn de enviar los resultados en esta pantalla.
Sub SendRequest () Send ("Content-type: text / html") Send ("") Send ("<HTML> <HEAD> <TITLE>") Send (". Por favor, introduzca su direccin de E-Mail") Enviar ("</ TITLE> </ HEAD>") Send
El VALOR palabra clave coloca el texto en el campo de entrada que puede ser til para sugerir lo que los usuarios deben rellenar all. Despus de eso, se configura alguno de los botones de radio usando ENTRADA TYPE = "radio" . Los botones de opcin se utilizan para permitir a los usuarios elegir una de varias opciones. Si desea agrupar un par de botones, se debe utilizar el mismo NOMBRE para todos ellos. Si desea crear dos grupos separados de botones de opcin, es necesario utilizar una diferente NOMBRE para los miembros de cada grupo. La variable, especificado por el identificador NOMBRE ( Male_or_Female , en este caso), contiene el VALOR del botn de radio controladas por los usuarios. El cdigo siguiente produce botones de seleccin de ambos sexos:
Enviar ("usted: MedlinePlus") Send ("<INPUT TYPE=""radio"" NAME=""Male_or_Female""" + _ "VALUE=""Male or"">") Send ("Male < br> ") Send (" <INPUT TYPE=""radio"" name="" Male_or_Female""
Si el usuario no selecciona cualquiera de los botones, el NOMBRE identificador estar ausente, y tratando de descifrar utilizando la GetSmallField () funcin genera un error. Se aprende ms acerca de esta situacin en la que decodificar estos campos ms adelante en la seccin "Advanced Forms Decoding". Otra manera de permitir a los usuarios elegir una de varias opciones es el uso de un cuadro de seleccin. Este mtodo es especialmente til cuando usted tiene varias opciones para elegir y usted quiere que su forma de permanecer legible y compacta. Puede configurar un cuadro de seleccin para seleccionar la que el usuario vive, de la siguiente manera:
Enviar ("<p>") Send ("Dnde vives?") Send ("<ELIJA NAME=""Continent"">") Send ("<OPTION seleccionada> Amrica del Norte") Send ("<OPTION> Europa ") Send (" Otros <OPTION> ") Send (" </
El cuadro de seleccin se identifica por NAME = "continente" y est lleno de opciones mediante la OPCIN palabra clave. Slo tres opciones se utilizan aqu, pero prcticamente se puede utilizar las opciones de todas las que quieras. Cuando haya terminado de llenar el cuadro de seleccin, se utiliza el / SELECT palabra clave. (Tenga en cuenta que una opcin utiliza el SELECTED . palabra clave Esta opcin es la predeterminada, se muestra como preseleccionado). A veces, desea que los usuarios elegir ms de una de las opciones disponibles. En esta situacin, utilice las casillas de verificacin para permitir a los usuarios elegir entre varias acciones-que se agregan a una lista de correo, se envan ms informacin, y que se llama:
Enviar ("Por favor, marque uno o ms de los siguientes: MedlinePlus") Send ("tipo de entrada <=" "checkbox" "NAME =" "Accin" "" + _ "VALUE =" "aadir a nuestra lista de correo" ">") Sen
Las casillas de verificacin todos tienen el mismo identificador, "Accin" . Esta variable contiene el VALOR que ha sido especificado por una casilla marcada por los usuarios. Debido a que los usuarios pueden marcar ms de una casilla, el identificador se enumeran. Por lo tanto, si los usuarios marcar todas las casillas, aparece el identificadores de Accin , Action_1 y Action_2 , que todos tenemos que ser decodificado por separado por la aplicacin CGI. A veces, es posible que desee aadir algo a una forma que los usuarios no pueden ver, por ejemplo, un nmero de cuenta, el nmero de pizzas ordenado, y as sucesivamente. Usted puede agregar esta informacin mediante el uso de campos ocultos que no se muestran a los usuarios, pero puede ser decodificado al presentar sus formularios. Slo para ilustrar cmo los campos de trabajo oculto, agregue la hora actual. Puede utilizar esta informacin para guardar el momento en que se pidi a la forma por un usuario:
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 6 de 11
Por el momento, guardar el proyecto, compilar el ejecutable y ejecutarlo mediante el explorador Web. Si todo va bien, se obtiene una forma como la que se muestra en la figura 21.5. Tenga en cuenta que el campo de nombre es pre-llenado con el valor especificado, el cuadro de seleccin muestra la opcin preseleccionada, y el campo de hora no se muestra. La figura. 21,5 Despus de ejecutar la aplicacin email.exe, la pgina resultante debe ser algo como esto.
Sub sendResponse () Email As String Nombre As String Dim Male_or_Female Como Continente Cadena As String Dim Accin Como Your_Time String Dim As String Dim n = Email GetSmallField ("Emai
La primera cosa que puede atraer su atencin es la forma de descifrar los botones de radio:
On Error Resume Next Male_or_Female = GetSmallField ("Male_or_Female") On Error GoTo 0
Ya habas aprendido que el campo de botn de opcin es inexistente cuando no tocado por los usuarios y que la GetSmallField funcin genera un error en un campo no existente. Por lo tanto, es necesario utilizar la captura de errores. Los On Error trampas de la declaracin del error y realiza una tarea especificada detrs de la declaracin. Por lo tanto, si la lnea siguiente genera un error,
Male_or_Female = GetSmallField ("Male_or_Female")
el programa descarta esta lnea y contina con la ejecucin de la lnea siguiente como se especifica en el On Error comunicado. La variable Male_or_Female luego se queda vaca. La lnea siguiente se restablece el error handler:
On Error GoTo 0
El marco cgi32.bas tambin contiene las rutinas de control de errores, por lo que reiniciar el controlador de errores a sus valores predeterminados es una buena idea. El cuadro de seleccin se decodifica con bastante facilidad, similares a los campos de entrada normal:
Continente = GetSmallField ("Continente")
Las casillas de verificacin son decodificados tambin de una manera especial. Dependiendo del nmero de casillas marcadas, ms o menos campos de accin se enumeran ( Accin , Action_1 , Action_2 , y as sucesivamente). No se puede predecir cuantos campos haya, el nmero de campos depende del nmero de casillas marcadas. Porque he visto que la decodificacin de un campo no existente genera un error, es necesario utilizar la interceptacin de errores, tambin. Usted puede construir un Do Loop en la que se lee secuencialmente Accin , Action_1 , Action_2 , y as sucesivamente hasta que el GetSmallField () funcin genera un error (en un campo no existente). A continuacin, atrapar el error en la Done_Decoding rutina. Esto entonces hace un salvador llamar al Done_Decoding1 rutina, que restaura el controlador de errores:
On Error GoTo Done_Decoding hacer si n = 0 Entonces Action = "Haremos lo siguiente:" & GetSmallField ("Accin") ELSE = Accin y Accin "y" & GetSmallField ("Action_" & n) End If n = n +
Este enfoque puede parecer poco prctico, a primera vista, sin embargo, funciona bien, y no hay otra forma sencilla de hacerlo con tanta fiabilidad como este. Tenga en cuenta que usted est construyendo una frase dentro del bucle Do que contiene las acciones de los usuarios solicitados. El campo oculto se lee mediante el uso de una normal GetSmallField () llame al:
Your_Time = GetSmallField ("Time")
Todos los datos que ha sido descodificada se enva de vuelta al usuario, como sigue:
Enviar ("Gracias por enviar tu E-Mail MedlinePlus!") Send ("<pre>") Send ("Hemos registrado:" + mail + "<br>") Send ("su nombre:" + Nombre + "<br>") Send ("Usted es:" + + Male_or_Female
Se utiliza el <pre> tag HTML para alinear la salida correctamente. Ahora que ha terminado de editar el sendResponse procedimiento, guarde el proyecto, compilarlo y ejecutarlo. Envo de una forma de los resultados de los proyectos de email en una respuesta como la que se muestra en la figura 21.7. La figura. 21,7 Despus de que el usuario rellene en algunos campos del formulario generado por la aplicacin email.exe y haciendo clic en el botn Enviar, esto es como una respuesta podra ser.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 7 de 11
Usted quiere crear una base de datos con capacidad de bsqueda Web por muchas razones. Supongamos que usted tiene una gran base de datos que desea que sean accesibles para todas las personas en su empresa. Debido a que los empleados probablemente trabajar con varias plataformas informticas diferentes (tales como PC, Mac y UNIX), es necesario tener aplicaciones cliente desarrolladas para todas las plataformas que utilizan. Incluso si usted tiene xito en conseguir una aplicacin para todas las plataformas, puede gastar decenas de miles de dlares en la obtencin de licencias de software, la contratacin de programadores, y as sucesivamente. Por qu no escribir un script CGI que tiene acceso a su base de datos? Navegadores web gratuitos estn disponibles para todas las plataformas de ordenador. Un servidor Web no debe costar mucho, ni tampoco el PC se ejecuta en cualquiera de los dos. Si la informacin en la base de datos es confidencial, puede restringir el acceso a su base de datos del mundo exterior por medio del filtrado de IP o una combinacin de nombre de usuario / contrasea. Esto se discute ms adelante en la seccin "Consideraciones de seguridad Visual Basic".
La Base de Datos
En primer lugar, se necesita una base de datos. Debe contener algunos registros con los nombres, nmeros de telfono y direcciones de correo electrnico para ilustrar cmo funciona el acceso a datos con Visual Basic. En principio, se puede usar uno de los sabores de bases de datos mencionados anteriormente o una base de datos para el que tenga un controlador ODBC. En este ejemplo, he utilizado una base de datos Access 2.0, pero discutir donde se debe modificar el cdigo para su uso con otras bases de datos. Se puede obtener la base de datos necesaria para este ejemplo de dos maneras:
z
Copie la base de datos phone.mdb desde el CD en CGI-WIN directorio de su servidor. No se puede utilizar la base de datos directamente desde el CD, porque el motor de base de datos tiene que ser capaz de escribir en la base de datos. Crear la base de datos utilizando Microsoft Access. Tenga en cuenta que usted tiene que hacer esto slo si no se puede copiar la base de datos desde el CD. Para efectos de este ejemplo, estoy asumiendo que usted est utilizando Access 2.0, aunque otras versiones de Access funcionan de manera similar. Inicie Access. A continuacin, cree una nueva base de datos mediante la apertura de la F ile men y eligiendo N ew Database. Nombre de la base de datos phone.mdb y situarla en CGI-WIN directorio de su servidor. Haga clic en el N ew botn mientras la ficha Tabla se activa y elija Nueva tabla. A continuacin, se crea la tabla. Ahora aade tres nuevos campos, escriba el nombre Nombre , PHONE_NUMBER y EMAIL_ADDRESS en tres celdas separadas campo Nombre. El tipo de datos tiene que ser para todos los campos de texto (que es el predeterminado). A continuacin, cierre la tabla y elija Y es despus pide que guarde la tabla. Nombre de la tabla my_table , y si se le pregunta por ello, decide crear una clave principal. Utilice el O botn del lpiz mientras la ficha Tabla se activa para abrir la tabla y empezar a aadir nombres, nmeros y direcciones de correo electrnico. La base de datos debera parecerse a la figura 21.8. En este punto, usted ha creado una base de datos llamada phone.mdb, que contiene la tabla my_table con el nombre de los campos de texto, PHONE_NUMBER y EMAIL_ADDRESS.
La figura. 21,8 Una vez que haya creado con xito una base de datos con Access 2.0, los resultados deben ser algo como esto. Ahora que usted tiene su base de datos, puede empezar a escribir la solicitud de acceso a datos. La primera parte es similar a la aplicacin de correo electrnico que ha creado anteriormente. Abra Visual Basic. A continuacin, abra la F ile men y seleccione N ew para iniciar un nuevo proyecto. Si tiene cualquier forma, retrelos con la apertura de la F ile men y elegir R Archivo emove. Hacer lo mismo para los mdulos (si los hay). A continuacin, abra la T erramientas men y seleccione R eferencias. En el cuadro de dilogo Referencias, desmarque la MS de objetos DAO 3.0 elemento de la biblioteca, seleccione el tem MS DAO 2.5 Object Library y cerrar el cuadro de dilogo. Esto es para asegurar que VB utiliza el motor de base de datos adecuada. Agregar el marco cgi32.bas a su proyecto mediante la apertura de la F ile men y escoger un d archivo d. Los cgi32.bas debe estar en el directorio cgi-src su servidor Web. A continuacin, agregue el mdulo que contiene el cdigo de acceso a datos. Abra la I nsert men y seleccione M dulo para agregar el mdulo. Visual Basic lo Module1 nombres. Al igual que con la aplicacin de correo electrnico, aadir un Inter_Main procedimiento escribiendo lo siguiente en la general-declaraciones seccin de Module1:
Sub Inter_Main
Luego, en la general-declaraciones seccin de Module1, agregue el cdigo que se muestra en el listado 21.9.
Listado 21,9 phone.vbp: El CGI_Main Procedimiento de phone.bas
Sub CGI_Main () Si CGI_RequestMethod = "GET" Entonces SendRequest Exit Sub End dems SendResults Exit Sub If End Sub
Cuando los usuarios acceden a la secuencia de comandos CGI, por primera vez utilizando un GET mtodo de peticin, el SendRequest procedimiento se ejecuta. Este procedimiento genera un formulario. Cuando los usuarios envan una consulta mediante el POSTE mtodo de la peticin, el SendResults procedimiento se llama, que contiene el cdigo real de los datos de acceso. A continuacin, agregue el SendRequest procedimiento a Module1 como se muestra en el listado 21.10.
Listado 21,10 phone.vbp: El SendRequest Procedimiento de phone.bas
Sub SendRequest () Send ("Content-type: text / html") Send ("") Send ("<HTML> <HEAD> <TITLE>" y "base de datos Nmero de telfono" & _ "</ TITLE> </ HEAD > ") Send (" <BODY> ") Send (" <
El SendRequest procedimiento genera un formulario con un campo de entrada de 30 caracteres de ancho consulta con nombre. Dado que este ejemplo es esencialmente el mismo que el ejemplo de correo electrnico, puede moverse rpidamente en el procedimiento de bsqueda real llamado SendResults . Ingrese el cdigo que se muestra en el listado 21.11.
Listado 21,11 phone.vbp: El SendResults Procedimiento de phone.bas
Sub SendResults Db Dim Dim tmpDyna como base de datos como consulta Dynaset As String Dim SQLQuery como consulta String = GetSmallField ("query") Send ("Content-type: text / html") Send
Ahora usted tiene todo lo que necesita para buscar una base de datos en Visual Basic y enviar los resultados a los usuarios. Simple, no? Debido a que es posible que desee crear su propia base de datos de bsqueda en la Web, le explico todo el cdigo utilizado aqu. Si usted entiende cmo funciona este cdigo, se puede adaptar para usar con su propia base de datos. El SendResults rutina comienza con la decodificacin del campo de consulta:
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 8 de 11
A continuacin se incluyen algunas lneas de cdigo HTML para generar un formulario de respuesta:
Enviar ("Content-type: text / html") Send ("") Send ("<HTML> <HEAD> <TITLE>" y "base de datos de nmero de telfono" & _ "</ TITLE> </ HEAD>") Enviar ("<BODY>")
A continuacin, abra la base de datos mediante el uso de Visual Basic OpenDatabase () funcin. Tiene la siguiente sintaxis:
Set db = OpenDatabase (dbname [, [exclusivo de slo lectura [, origen]]])
db Este es el nombre de un objeto que ha sido declarado como un objeto de base de datos con un Dim comunicado. dbname Esta cadena contiene una ruta o una ruta de red a una base de datos Visual Basic admite directamente o el nombre de un origen de datos ODBC. exclusivo Este valor booleano determina si la base de datos se abre como exclusiva, es decir, si otras aplicaciones se les permite abrir la base de datos al mismo tiempo. En general, se debe configurar el exclusivo valor a Falso porque permite que ms de un usuario para buscar en su base de datos al mismo tiempo. de slo lectura Este valor booleano determina si la base de datos se va a abrir con lectura / escritura o acceso de slo lectura. Usted debe establecer este valor en False menos que desee alterar la base de datos con la aplicacin CGI. fuente Esta cadena contiene toda la informacin adicional que se necesita para abrir la base de datos. Esta informacin podra ser un nombre de inicio de sesin, una contrasea, y as sucesivamente. Si dejas el dbname cadena vaca y establecer el origen de cadena a "ODBC" , un cuadro de dilogo en el que puede buscar un
certificado de origen de datos ODBC. Esta caracterstica es particularmente til cuando se tiene problemas al abrir una base de datos con un controlador ODBC. La documentacin que viene con un controlador particular debe proporcionar ms informacin sobre cmo abrir una base de datos. Para este ejemplo, la siguiente lnea se utiliza para abrir la base de datos:
Set Db = OpenDatabase ("cgi-win \ phone.mdb", False, True)
Db
Db As Database
Debido a que situar la base de datos phone.mdb en cgi-win directorio del servidor, se utiliza la siguiente ruta de acceso a la misma: "cgi-win \ phone.mdb" . Si tiene problemas, usted debe cambiar a la ruta completa, que puede ser similar al siguiente:
"C: \ website \ cgi-win \ phone.mdb"
La ruta completa, por supuesto, depende de la configuracin. Usted no tiene que colocar la base de datos en el directorio cgi-win de su servidor. Esto funciona siempre y cuando usted indica el camino correcto. Tambin puede utilizar un archivo de base de datos desde otro PC de la red. Usted debe especificar lo siguiente:
"\ \ Servidor \ directorio \ database.mdb"
Observe en el ejemplo que la base de datos se abre en modo no exclusivo y de slo lectura. Mediante el uso de estos modos, se permite a otras aplicaciones para abrir la base de datos de usuarios y mltiples para utilizar su Web con capacidad de bsqueda de base de datos al mismo tiempo. Debido a que slo est buscando y no alterar la base de datos, la apertura de la base de datos en modo de slo lectura es seguro. La fuente cadena se omite en este caso porque la base de datos no necesita ninguna informacin adicional para ser abierto. Como se vio anteriormente, es probable que tenga que especificar esta cadena slo cuando se est utilizando un controlador ODBC. Despus de abrir la base de datos, es necesario buscar los trminos que los usuarios han enviado. Puedes hacerlo en un par de maneras en Visual Basic, pero aqu se utiliza una consulta SQL.
Consulte "Generacin de cdigo SQL para transferir datos presentados," para obtener ms informacin acerca de SQL.
Esta consulta le dice al motor de base de datos de VB para seleccionar todos los registros de my_table tabla para la que el campo Nombre contiene la cadena de consulta . El asterisco (*) comodn antes y despus de la cadena de consulta de la bsqueda del motor de base de datos para coincidencias de subcadenas. Esto significa que la consulta selecciona todos los registros que contengan la cadena de consulta, no slo las que coincidan exactamente. As que si usted busca '* fred *' , no slo la base de datos del motor de registros seleccionados coincidan con Fred , pero tambin selecciona Alfred y Frederique . Del mismo modo, tambin se puede usar? # como un solo carcter y un solo dgito (0-9) comodines, respectivamente. De manera predeterminada, las consultas SQL en VB se distingue entre maysculas y minsculas. Sin embargo, algunos controladores ODBC se distingue entre maysculas y minsculas.
SQL en Visual Basic vara ligeramente de ANSI (estndar) de SQL. Si est utilizando un controlador ODBC o llamadas directas ODBC.DLL API, puede que tenga que utilizar el equivalente ANSI de los comodines mencionados aqu: Visual Basic SQL ANSI SQL Equivalente ? _ (Guin bajo) * %
La comilla simple ( ' ) tiene un significado especial en Visual Basic. Se utiliza para agregar comentarios en el cdigo fuente de Visual Basi
SQLQuery = "SELECT * FROM WHERE Nombre my_table como" & "'*" & query _ & "*'"
Si desea utilizar su propia base de datos, puede realizar cambios en my_table Nombre y dejar que el motor de bsqueda de base de datos la tabla correcta y nombres de campo.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 9 de 11
Un Dynaset es una parte dinmica de la base de datos que coincide con los criterios de la consulta SQL. En primer lugar, comprobar si la bsqueda devuelve nada por usar el RecordCount mtodo. Si el Dynaset no contiene registros coincidentes, se enva un mensaje corto que la bsqueda ha fallado:
Si tmpDyna.RecordCount = 0 y luego enviar ("Su bsqueda no produjo resultados. <br>")
Si el Dynaset no est vaco, lea la Dynaset registro por registro utilizando el MoveNext mtodo dentro de un Do Loop . El Do Loop se interrumpe tan pronto como el final de la Dynaset se alcanza. Esto se hace mediante la lectura de la EOF de la propiedad Dynaset , que es cierto despus de que el ltimo registro que se lee:
Do While Not tmpDyna.EOF Enviar ("<PRE>") Send ("Nombre:" & tmpDyna ("Nombre")) Send ("Nmero de telfono:" & tmpDyna ("PHONE_NUMBER")) Send ("Direccin de correo electrnico:" y tmpDyna
tmpDyna
En cada ciclo de la Do Loop , todos los tres campos (Nombre, PHONE_NUMBER, y EMAIL_ADDRESS) para el registro actual se leen mediante una llamada al Dynaset con el nombre del campo como un argumento. (Si utiliza otra base de datos, usted debe, por supuesto, Cambio de nombre, PHONE_NUMBER y EMAIL_ADDRESS a los nombres de campo correctas.) Ahora ests acabado con el telfono en la Web de bsqueda de base de datos. Para guardar el proyecto, abra el F ile men y seleccione Sa v e Project. El nombre de su proyecto phone.vbp y nombre Module1 phone.bas . A continuacin, abra la F ile men y elegir Ma k archivo EXE e para compilar su proyecto. El nombre de su proyecto Phone.exe y colocarlo en el directorio cgi-win de su servidor. (Tambin puede encontrar el archivo de proyecto y phone.vbp phone.bas los archivos bsica en el CD-ROM que viene con este libro.) Ejecutar Phone.exe apuntando el navegador web a la siguiente URL:
z
Reemplace your.servers.address con la direccin de Internet de su servidor, o si se ejecuta el navegador Web en el mismo equipo que el servidor Web se encuentra activado, puede utilizar el nmero de IP de bucle invertido 127.0.0.1 . (Si su equipo no est conectado a Internet, es necesario utilizar el nmero de IP de bucle invertido.) Su completa base de datos con capacidad de bsqueda Web nmero de telfono debe parecerse a la Figura 21.9 en su navegador Web. La figura. 21,9 La aplicacin Phone.exe CGI genera un formulario como el siguiente. Ahora escriba algo en el campo y haga clic en Buscar. Los resultados de una bsqueda de la carta una se muestra en la figura 21,10. Todos los nombres que contienen un una se enumeran. Tambin puede escribir un nombre como Pablo o Carl, pero este ejemplo ilustra mejor cmo la aplicacin busca subcadenas. La figura. 21,10 Despus de buscar la 'a' a la aplicacin Phone.exe, los resultados deben ser algo como esto. He recibido el mensaje de error No se pudo encontrar el archivo 'cgi-win \ phone.mdb'. (error # 3024) . Qu est pasando? Este mensaje indica que la ruta especificada en la lnea que contiene el OpenDatabase declaracin en el procedimiento SendResults de phone.bas es incorrecta. Debe cambiar cgi-win \ phone.mdb a la ruta completa de la base de datos. Cuando intento compilar el proyecto phone.vbp, un usuario definido tipo no definido error se genera. Durante la ejecucin del script, un Error Loading DLL mensaje se genera. Qu est pasando? Las referencias a las bibliotecas de Visual Basic de datos de objetos son incorrectos. Abra el F ile men y seleccione R eferencias. En el cuadro de dilogo Referencias, desmarque MS DAO 3.0 Object Library y seleccione MS DAO 2.5 Object Library. Dependiendo del tipo de base de datos, es posible que tenga que seleccionar la compatibilidad de Microsoft 2.5/3.0 elemento de biblioteca. He especificado la ruta correcta a la base de datos, pero la aplicacin sigue negndose a ejecutar. Qu ms podra estar mal? Si ha especificado la ruta correcta a la base de datos y la aplicacin de base de datos an se niega a acceder a la base de datos, usted debe asegurarse de que las bibliotecas de tiempo de ejecucin de Visual Basic para el acceso a los datos han sido correctamente instalado en el PC servidor. Incluso si usted sabe qu archivos son necesarios, no es suficiente con slo copiarlos en el disco duro de su servidor. Usted puede, por supuesto, instalar otra copia de VB en el servidor, pero hay una manera ms fcil. Usted puede utilizar el Asistente de instalacin de VB para preparar disquetes de instalacin con todas las bibliotecas que necesita. Si selecciona phone.vbp que el proyecto, el Asistente de configuracin incluye todas las bibliotecas de acceso a datos y el archivo setup.exe que se genera instala estas bibliotecas cuando se ejecuta en el PC servidor. Si est utilizando un controlador ODBC, asegrese de que usted lo ha configurado segn lo prescrito en la documentacin que se suministra con el conductor. Por defecto, 3 de Visual Basic no puede utilizar la base de datos de Access 2.0 incluido en el CD-ROM, ya que slo es compatible con el Access 1.0 y 1.1 formatos de base de datos. Sin embargo, despus del lanzamiento de Access 2.0, Microsoft public una capa de compatibilidad que permite 3 de Visual Basic para utilizar Access 2.0 bases de datos. Si tiene acceso a Internet, puede descargar la capa de compatibilidad en el sitio Web de Microsoft en este sitio . Tambin puede ponerse en contacto con su distribuidor local de Microsoft.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 10 de 11
El envo de informacin confidencial a travs de una red pblica es siempre arriesgado. Usted no quiere tener clientes que presenten sus nmeros de tarjetas de crdito a travs de Internet sin proteccin. Los piratas informticos pueden apoderarse de esta informacin. Afortunadamente, S-HTTP (Secure HTTP) y SSL normas (Secure Sockets Layer) se han desarrollado, por lo que con seguridad puede transportar datos a travs de una red pblica. Muchos navegadores web y los servidores Web de UNIX ya apoyan estas transacciones. La edicin profesional de la versin Web 1.1 tambin soporta transacciones seguras.
Consulte "Introduccin a SSL" e "Introduccin a S-HTTP" para obtener ms informacin sobre SSL y S-HTTP.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 11 de 11
rendimiento despus de actualizar la RAM de los 32M a 64M, especialmente en los sistemas Windows NT. Mejora del rendimiento de CGI por Precarga de archivos DLL en tiempo de ejecucin Una cuestin importante es la precarga de DLL. Visual Basic es un lenguaje interpretado , lo que significa que necesita las bibliotecas de tiempo de ejecucin durante la ejecucin, generalmente se llama bibliotecas de enlace dinmico o DLL. Estas bibliotecas son mdulos que Windows necesita para cargar en la memoria antes de una aplicacin de VB se puede ejecutar, y esto puede tomar hasta varios segundos. La aplicacin CGI se ejecuta ms rpido cuando estos archivos DLL se carga en la memoria de antemano, ya que esto le ahorra el tiempo de cargarlos en la solicitud de CGI. Muchos servidores Web puede precargar los archivos DLL en el arranque del servidor y guardarlos en la memoria durante el tiempo que se ejecuta el servidor. El servidor Web Website puede hacerlo cuando se utiliza el -l opcin de lnea de comandos. Por ejemplo, httpd32.exe -l vb40032.dll inicia el servidor Web y precarga de la biblioteca de tiempo de ejecucin de Visual Basic. Para otros servidores Web, consulte el manual para obtener informacin sobre este tema. Adems de vb40032.dll (la principal biblioteca de ejecucin de Visual Basic), es posible que desee cargar DLLs para otros ejemplo, si la aplicacin utiliza el acceso de base de datos. Sin embargo, lo que los archivos que necesita para precarga depende del tipo de base de datos que utiliza.
VBScript de Microsoft ser un subconjunto de Visual Basic que est optimizado para los navegadores Web. El cdigo de Visual Basic puede ser embebido dentro del documento HTML. Una biblioteca de tiempo de ejecucin pequeo ser llamado por el navegador cuando recibe una secuencia de comandos de Visual Basic. La biblioteca de tiempo de ejecucin puede ser objeto de licencia de forma gratuita. Imagnese que usted est vendiendo CDs en Internet, y desea que sus formas de sumar los costos totales, mientras que el usuario est reuniendo adquisiciones. Usted ser capaz de aadir un script como el siguiente formulario:
<SCRIPT> Sub CheckBoxLouReed.Click TotalAmount.Text = CStr (Val (TotalAmount.Text) + 19.99) End Sub </ script>
Tenga en cuenta que esto es slo un ejemplo ilustrativo. Incluso los HTML <SCRIPT> etiquetas todava tienen que ser negociados con las normas de alcance mundial Web comits. La ventaja principal de Visual Basic Script es que es tan intuitiva y fcil de aprender como Visual Basic. Si usted ha hecho algo de programacin Visual Basic antes, es probable que se de programacin Visual Basic Script en ningn momento. JavaScript es otro lenguaje de script que est siendo implementado en el navegador Netscape. A diferencia del lenguaje Java, que se compila en el lado del servidor, JavaScript es interpretado en el lado del cliente. Debido a que es orientado a objetos, JavaScript tiene ms de un C + +-tipo de enfoque y requiere conocimientos de programacin un poco ms avanzados. Las implementaciones de JavaScript para servidores web tambin estar disponible como alternativas para CGI. Un debate en curso es la forma segura estos lenguajes de scripting son. Podra alguien escribir un virus informtico en un lenguaje de script y borrar su disco duro? Los desarrolladores de JavaScript se han ocupado de esta cuestin de antemano por no permitir el acceso de escritura en el disco duro. Sin embargo, he odo hablar de un JavaScript que recopile y presente de los usuarios de correo electrnico de los destinatarios a un servidor como una manera rpida y sucia de hacer investigacin de mercado. Algunas otras restricciones relacionadas con estos lenguajes de script estn en su lugar. Supongamos que usted no desea compartir el cdigo fuente de su script con el resto del mundo. Esto es imposible con VBScript y JavaScript, ya que la fuente se enva al usuario cuando accede a su servidor, sino que est incrustada en el documento HTML e interpretado por el navegador Web del usuario. En el caso de una secuencia de comandos que accede a una base de datos, necesitar enviar la base de datos junto con la secuencia de comandos, que es, por supuesto, indeseables. Estos lenguajes de secuencias de comandos sin duda ser til para algunas aplicaciones; para otras aplicaciones, usted todava tendr que confiar en CGI. Aviso de Copyright: Los proyectos de Visual Basic en este captulo utilizan el cgi32.bas Visual Basic CGI marco de Robert Denny, que es autor [cw] 1995, O'Reilly & Associates, Inc., todos los derechos reservados, y se reproduce con permiso de O'Reilly & Associates. Captulo Anterior <- Contenido -> Siguiente Captulo QUE Pgina de inicio Para obtener soporte tcnico para nuestros libros y contactar software support@mcp.com Copyright 1996, Que Corporacin
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 1 de 14
Copyright 1996, Que Corporation. All rights reserved. No part of this book may be used or reproduced in any form or by any means, or stored in a database or retrieval system without prior written permission of the publisher except in the case of brief quotations embodied in critical articles and reviews. Making copies of any part of this book for any purpose other than your own personal use is a violation of United States copyright laws. For information, address Que Corporation, 201 West 103rd Street, Indianapolis, IN 46290 or at support@mcp .com. Notice: This material is excerpted from Special Edition Using CGI, ISBN: 0-7897-0740-3. The electronic version of this material has not been through the final proof reading stage that the book goes through before being published in printed form. Some errors may exist here that are corrected before the book is published. This material is provided "as is" without any warranty of any kind.
What the Windows CGI standard is and how it differs from standard (UNIX) CGI What the input and output files of Windows CGI are and how they're decoded What the cgi32.bas framework is How to set up a Windows CGI application using Visual Basic How to create forms How to process submitted data How to access a database using Visual Basic How to set up a Web-searchable phone number database
You can download several try-before-you-buy versions of the Web servers. You can obtain the Website Web server, which runs under Windows 95 and Windows NT, from this site. You can even install a Web server on a PC that isn't connected to the Internet and use the loopback IP address to access it (http://127.0.0.1). Read the documentation that comes with your Web server on how to install it on your system.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 2 de 14
You can easily order a pizza online. The user's Web browser contacts your server and submits the data that was filled in the fields and the path of the CGI application that handles the request. Figure 21.2 shows what happens when the user submits the data. Fig. 21.2 During a Windows CGI request, the server launches an application that processes an input file and sends results to an output file. The output file is subsequently sent back by the server. After all data is sent by the user's Web browser, the server launches the CGI application. This is done using the following command-line syntax:
cgi-application cgi-data-file content-file output-file url-args
This parameter is the full path to the CGI application that's usually a Windows executable. In practice, CGI applications are located in a separate directory. This directory is inaccessible from the Internet, so no one can download the executable. This directory is usually set in the server's setup. If your Windows CGI directory is set to CGI-WIN, the path could be something like c:\website\cgi-win\order.exe. cgi-data-file This parameter is the path to the file containing all data concerning the request. It contains fields submitted by the user (what size, the user's address, and so on) and some information about the connection (the Internet address and the type of Internet software of the user, for instance). This data is read by the CGI application after it's launched. The file is placed in your temporary directory. content-file The content file contains any content that was submitted during the user's request. It could, for instance, contain a file that the user uploaded. It's almost never used by CGI programmers because it contains raw data. This file is placed in your temporary directory. output-file This parameter is the path to the output file; it's used to pass data from the CGI application to the server. This data could be a confirmation that the order is accepted. The server sends this data to the user, so usually it's in HTML format. url-args This parameter is anything that follows a ? (question mark) in the URL requested by the user. If no URL argument is present, this parameter is omitted from the command line. Some CGI database search scripts use URL arguments.
cgi-application
So what happens after the server launches the CGI application? The CGI application initializes and reads the data from the input file. Depending on the input, the application generates an output file. Suppose that all fields have been filled in properly by the user and that the order can be acknowledged. The CGI application then writes order accepted to the output file and exits. The Web server notices that the CGI application has ended, reads the output file, and sends the data from the output file back to the user.
[CGI] Request Protocol=HTTP/1.0 Request Method=GET Executable Path=/cgi-win/order.exe Server Software=WebSite/1.0 Server Name=server.domain.com Server Port=80 Server Admin=user@mailserver.com CGI Version=CGI/1.2 (Win) Remote Address=123.123.123.123 Authentication Method=Basic Authentication Realm=Web Server [System] GMT Offset=3600 Debug Mode=No Output File=c:\temp\59ws.out [Accept] image/gif=Yes image/x-xbitmap=Yes image/jpeg=Yes image/pjpeg=Yes */*=Yes [Extra Headers] Connection=Keep-Alive User-Agent=Mozilla/2.0b3 (Win95; I) Pragma=no-cache Host=123.123.123.123
If you focus on the [CGI] section, a couple of things may attract your attention: one of them is Request Method. The user requests this method to be performed by the server (GET in this case).
See "Request-Specific Environment Variables," for more information on request methods.
As you can see, the input file contains more interesting information. In the [Extra Headers] section, you can detect the type of Web browser of the user. The User-Agent item tells you that a Netscape 2.0 browser running under Windows 95 is used (Mozilla is the name that the Netscape developers use for their browser). The user's Internet IP address is shown after the Host item (it's 123.123.123.123 in this case). You can use all this data in your CGI application. Listing 21.2 shows another input file.
Listing 21.2 Input File for a User's POST Request
[CGI] Request Protocol=HTTP/1.0 Request Method=POST Executable Path=/cgi-win/order.exe Server Software=WebSite/1.0 Server Name=server.domain.com Server Port=80 Server Admin=user@mailserver.com CGI Version=CGI/1.2 (Win) Remote Address=123.123.123.123 Authentication Method=Basic Authentication Realm=Web Server Content Type=application/x-www-form-urlencoded Content Length=115 [System] GMT Offset=3600 Debug Mode=No Output File=c:\temp\5ews.out
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 3 de 14
Content File=c:\temp\5ews.inp [Form Literal] size=large extra=cheese name=Danny Brands address=123 Main St. phone=1-234-567 [Accept] image/gif=Yes image/x-xbitmap=Yes image/jpeg=Yes image/pjpeg=Yes */*=Yes [Extra Headers] Connection=Keep-Alive User-Agent=Mozilla/2.0b3 (Win95; I) Host=127.0.0.1
The input file now mentions Request Method=POST. In this case, a user submits data, as shown in the [Form Literal] section. As you can see, he has ordered a pizza. The address, phone number, what kind of pizza-the information is all there.
Be careful with the cgi32.bas file because you use it in all projects. In principle, you never need to edit this file. Now add a Basic file in which you can place your own code. Open the Insert menu and choose Module to add a Basic file to the project. Visual Basic names it Module1 for you. You should never add a form to a CGI application; it relies on input and output files and never needs to open a window during execution. A form will slow down execution of your application. Now you're ready to create the procedure that starts execution after the CGI executable is launched by the server. This procedure is called CGI_Main. When you're reviewing an existing CGI application, you should always start looking in this procedure. Open the code window of Module1. Make sure that you're in the general-declarations section of Module1; then create the CGI_Main procedure by typing the following:
Sub CGI_Main
Visual Basic then creates the procedure for you. In the same way, create an Inter_Main procedure in the general-declarations section of Module1 by typing this line:
Sub Inter_Main
The Inter_Main routine is used only when the script isn't executed by a Web server, and you don't use this routine in this project. However, cgi32.bas contains a call to the Inter_Main subroutine, and you can't compile the project without it.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 4 de 14
you're in the general-CGI_Main procedure of Module1. Then add the code shown in bold in listing 21.3 (everything between the Sub CGI_Main() and End Sub lines).
Listing 21.3 The CGI_Main Procedure of email.bas
Sub CGI_Main() If CGI_RequestMethod = "GET" Then SendReQuest Exit Sub End If End Sub
This code results in the SendReQuest procedure being called when the user requests the GET method. In this procedure, you generate an HTML document. Next, add the SendReQuest procedure. In the general-declarations section of Module1, enter all the code shown in listing 21.4. (Visual Basic creates the SendReQuest procedure for you after you type the Sub SendRequest line.)
Listing 21.4 The SendReQuest Procedure of email.bas
Sub SendReQuest() Send Send Send Send Send Send Send Send Send Send Send Send Send Send ("Content-type: text/html") ("") ("<HTML><HEAD><TITLE>") ("Please fill in your e-mail address.") ("</TITLE></HEAD>") ("<BODY>") ("<FORM METHOD=""POST"" ACTION=""/cgi-win\email.exe"">") ("") ("Please fill in your E-mail address and press submit.") ("<INPUT SIZE=30 NAME=""EMailAddress"">") ("<INPUT TYPE=""submit"" VALUE=""Submit"">.") ("") ("</FORM>") ("</BODY></HTML>")
End Sub
Next, the contents of the SendRequest procedure will be discussed. You may have noticed that you use the Send() routine to write data to the output file; this routine is defined in the cgi32.bas framework. The SendRequest procedure begins with the following line:
Send ("Content-type: text/html")
The users' Web browsers need to know what kind of data is being sent. In this case, you send HTML, but you could also send a GIF picture, a sound file, a binary executable, and so on, as long as you indicate this with the correct content-type. If you forget to include a content-type HTML statement, an error is generated. Starting an HTML page with a title is a good custom. The title is shown on the title bar of the users' Web browsers after the HTML document is loaded. The title is added with the following code:
Send ("<HTML><HEAD><TITLE>") Send ("Please fill in your e-mail address.") Send ("</TITLE></HEAD>")
To set up a form in HTML that can be submitted to a server, you need to specify the FORM METHOD, which tells the users' Web browsers what method to request. In this case, the users' Web browsers perform a POST request. What's more, you see what action will be performed. The users contact the server and request it to execute the email.exe file (your CGI executable). You could specify the full URL to your server, too, but you would have to change the script when you move it to another server. The way the URL is specified now, the user's browser will fill in the rest of the URL. In this case, the following is used:
Send ("<FORM METHOD=""POST"" ACTION=""/cgi-win\email.exe"">")
This line contains two double quotation marks. In Visual Basic, quotation marks have a special meaning. If you specify two double quotation marks, Visual Basic ignores the first and regards the second as a plain text quotation mark. For instance, METHOD=""POST"" results in METHOD="POST" being sent to the users. Next, you create an input field in which the users can fill in their e-mail addresses:
Send ("<INPUT SIZE=30 NAME=""EMailAddress"">")
The input field is 30 characters wide and is described by the identifier EMailAddress. You can add several other options, which are discussed later. For now, you can be satisfied with this simple field. The only thing you need to add is a Submit button:
Send ("<INPUT TYPE=""submit"" VALUE=""Submit"">.")
Notice that this button is another input type. The caption put on the button is determined by the VALUE variable; in this case, the caption is "Submit". Ending the HTML form with the proper syntax is a good custom:
Send ("</FORM>") Send ("</BODY></HTML>")
Now you can save your project and prepare the CGI executable. Save the project by opening the File menu and choosing Save Project. Save Module1 (the module you added to the project) as email.bas and the project as email.vbp. You can save these files in a separate directory or in your server's CGI-SRC directory. Next, compile the .EXE file by opening the File menu and choosing Make Exe. Name the executable email.exe and place it in your server's CGI-WIN directory or any other directory that's enabled for Windows CGI. This directory is usually set during the install procedure of your server but can be changed afterward (consult your server's manual). Now, you can access the CGI executable using your Web browser. Point your Web browser to the following URL:
z
http://your.servers.address"/cgi-win\email.exe
Replace your.servers.address with the Internet address of your Web server; if you run your Web browser and server on the same machine, you can use the loopback IP number: 127.0.0.1. (If your machine isn't connected to the Net, you do need to use the loopback IP number.) Make sure that you use a backslash (\) in the path name; many problems arise from using a forward slash (/) instead. If everything goes well, you end up with a form as shown in figure 21.3.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 5 de 14
Fig. 21.3 After running the email.exe application with a web browser, the results should look like this. I pointed my Web browser to the CGI script but nothing happens. What's going wrong? Don't panic yet. First, make sure that your Web server is running and that you've supplied the correct URL for your server. If you run the server and the Web browser on the same PC, you can use the loopback IP number (127.0.0.1) as the IP address. That you can access normal HTML files on the server is a good indication that you have the right IP address and that your server is properly running. Then convince yourself that you've placed the email.exe file in a directory that's enabled for Windows CGI applications. You can't run CGI applications from standard HTML directories on the server (such as \htdocs). Files in HTML directories are read by the server; CGI applications are executed, which is why a special directory needs to be configured for Windows CGI files. Generally, this directory is called \cgi-win. I have the impression that the application runs okay, but the server complains about Empty output from CGI program. You can't place a Windows CGI executable in a Standard CGI directory. The server uses a different method for launching these types of CGI applications. Whether a directory is enabled for Windows or Standard CGI is set in your server's setup, so you should consult your server's manual on this matter. With most Web servers, precompiled CGI executables are distributed. If you can run these files, chances are high that something is wrong within your Windows CGI executable. If you can run other CGI executables, you should check whether the version of your cgi32.bas file is recent. These scripts have been tested with version 1.7, but should in principle work with older and newer versions. Anyway, trying a newer version can't hurt. Recent versions of cgi32.bas are distributed with the Website Web server, and you can obtain them from the Internet at this site. Most problems with Visual Basic CGI scripts arise from the fact that people use the outdated cgi.bas instead of the newer cgi32.bas file in the 32-bit Visual Basic 4 environment. cgi.bas uses calls to the 16-bit Windows API, so you can't compile applications that use cgi.bas in the 32-bit VB 4 environment. You should remove the cgi.bas file and replace it with a recent version of the cgi32.bas file. If your Web server has been set up properly but the problem lies within your Visual Basic CGI application, you'll probably receive an error message after accessing the application with your Web browser. You can then try to solve the problem using this information.
Sometimes, errors occurring within your Visual Basic program are difficult to trace. Because the CGI application is called by the server, running your application from within the Visual Basic design environment isn't particularly useful. You can add the following line to the start of the CGI_Main procedure:
MsgBox("Hello World!")
When you compile the CGI application and execute it, a small box with the message Hello World! will appear on the server PC. The application halts on this line until you click OK. You can move the MsgBox line through your application until the error is generated before the box pops up. With a little experience, you can easily track down the line that generates the error.
Sub CGI_Main() If CGI_RequestMethod = "GET" Then SendReQuest Exit Sub Else SendResponse Exit Sub End If End Sub
The SendResponse procedure handles the POST requests. Next, enter the SendResponse procedure as shown in listing 21.6.
Listing 21.6 The SendResponse Procedure of email.bas
Sub SendResponse() Dim Email as String Email = GetSmallField("EMailAddress") Send Send Send Send Send Send Send Send Send ("Content-type: text/html") ("") ("<HTML><HEAD><TITLE> Thanks!") ("</TITLE></HEAD>") ("Thank you for submitting your e-mail address!") ("<br>") ("We have registered: " + Email) ("</FORM>") ("</HTML>")
End Sub
The following line is meaningful because it shows how you can read fields from the form that has been submitted by the users by using the GetSmallField() function, which is part of the cgi32.bas framework:
Email = GetSmallField("EMailAddress")
The GetSmallField() function is called with the name of the field as an argument. You might have noticed that EMailAddress is the name of the input field that you specified in the SendRequest subroutine:
Send ("<INPUT SIZE=30 NAME=""EMailAddress"">")
The variable Email is sent back to the users afterward using the following code (note that you've previously declared the Email variable by using a Dim statement):
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 6 de 14
Save and compile your project and run the CGI application by pointing your Web browser to the correct URL as you've done before. Then type something in the e-mail field and click Submit. If everything goes well, you see a response like the one shown in figure 21.4. Unlike what the result shows, you have, of course, not registered anything at this point. Fig. 21.4 Filling in an e-mail address and clicking the submit button results in this screen.
Sub SendReQuest() Send Send Send Send Send Send Send Send Send Send ("Content-type: text/html") ("") ("<HTML><HEAD><TITLE>") ("Please fill in your E-Mail address.") ("</TITLE></HEAD>") ("<BODY>") ("<FORM METHOD=""POST"" ACTION=""/cgi-win\email.exe"">") ("") ("Please fill in your E-mail address.") ("<INPUT SIZE=30 NAME=""EMailAddress"">")
Send ("<p>") Send ("Please type your name here:") Send ("<INPUT SIZE=30 NAME=""Name"" VALUE=""Your name here"">") Send ("<p>") Send ("Are you:<br>") Send ("<INPUT TYPE=""radio"" " "NAME=""Male_or_Female"" Send ("Male<br>") Send ("<INPUT TYPE=""radio"" " "NAME=""Male_or_Female"" Send ("Female?<p>") Send Send Send Send Send Send Send
+ _ VALUE=""Male"">") + _ VALUE=""Female"">")
("<p>") ("Where do you live?") ("<SELECT NAME=""Continent"">") ("<OPTION SELECTED>North America") ("<OPTION>Europe") ("<OPTION>Other") ("</SELECT> ")
Send ("<p>") Send ("Please check one or more of the following:<br>") Send ("<INPUT TYPE=""checkbox"" NAME=""Action"" " + _ " VALUE=""add you to our mailinglist"">") Send ("Please add me to your mailinglist.<br>") Send ("<INPUT TYPE=""checkbox"" NAME=""Action"" " + _ " VALUE=""send you more information"">") Send ("Send me more information.<br>") Send ("<INPUT TYPE=""checkbox"" NAME=""Action"" " + _ " VALUE=""call you"">") Send ("Call me.<p>") Send ("<INPUT TYPE=""Hidden"" NAME=""Time"" VALUE=""" + _ Time$ + """>") Send Send Send Send End Sub ("<INPUT TYPE=""submit"" VALUE=""Submit"">.") ("") ("</FORM>") ("</BODY></HTML>")
The VALUE keyword places text in the input field that can be useful to suggest what users should fill in there. After that, you set up some radio buttons using INPUT TYPE="radio". Radio buttons are used to let users choose one out of several options. If you want to group a couple of buttons, you should use the same NAME for all of them. If you want to set up two separate groups of radio buttons, you need to use a different NAME for the members of each group. The variable, specified by the identifier NAME (Male_or_Female, in this case), contains the VALUE of the radio button checked by the users. The following code results in male and female radio buttons:
Send ("Are you:<br>") Send ("<INPUT TYPE=""radio"" NAME=""Male_or_Female"" " + _ " VALUE=""Male or"">") Send ("Male<br>") Send ("<INPUT TYPE=""radio"" NAME="" Male_or_Female"" " + _ "VALUE=""Female"">") Send ("Female?<p>")
If the users don't check any of the buttons, the NAME identifier will be absent, and trying to decode it using the GetSmallField() function generates an error. You learn more about this situation when you decode these fields later in the section "Advanced Forms Decoding." Another way of letting users pick one out of several options is by using a select box. This method is particularly useful when you have several options to choose from and you want your form to stay readable and compact. You can set up a select box for selecting where the user lives, as follows:
Send Send Send Send Send Send Send ("<p>") ("Where do you live?") ("<SELECT NAME=""Continent"">") ("<OPTION SELECTED>North America") ("<OPTION>Europe") ("<OPTION>Other") ("</SELECT> ")
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 7 de 14
The select box is identified by NAME="continent" and is filled with options using the OPTION keyword. Only three options are used here, but you can virtually use as many options as you like. When you're finished filling the select box, you use the /SELECT keyword. (Note that one option uses the SELECTED keyword. This option is the default; it shows up as preselected.) Sometimes, you want the users to choose more than one of the available options. In this situation, use check boxes to let users choose from several actions-being added to a mailing list, being sent more information, and being called:
Send ("Please check one or more of the following:<br>") Send ("<INPUT TYPE=""checkbox"" NAME=""Action"" " + _ " VALUE=""add you to our mailinglist"">") Send ("Please add me to your mailinglist.<br>") Send ("<INPUT TYPE=""checkbox"" NAME=""Action"" " + _ " VALUE=""send you more information"">") Send ("Send me more information.<br>") Send ("<INPUT TYPE=""checkbox"" NAME=""Action"" VALUE=""call you"">") Send ("Call me.<p>")
The check boxes all have the same identifier, "Action". This variable contains the VALUE that has been specified for a box checked by the users. Because the users can check more than one box, the identifier is enumerated. Therefore, if the users check all boxes, you see the identifiers Action, Action_1, and Action_2, which all have to be decoded separately by your CGI application. Sometimes, you might want to add something to a form that users can't see-for example, an account number, the number of pizzas ordered, and so on. You can add this information by using hidden fields that aren't shown to the users but can be decoded when they submit their forms. Just to illustrate how hidden fields work, add the current time. You might use this information to store the time the form was requested by a user:
Send ("<INPUT TYPE=""Hidden"" NAME=""Time"" VALUE=""" + Time$ + """>")
For now, save your project, compile the executable, and run it by using your Web browser. If everything goes well, you get a form like the one shown in figure 21.5. Note that the name field is prefilled with the value you specified, the select box shows the option you preselected, and the time field isn't shown. Fig. 21.5 After you run the email.exe application, the resulting page should look something like this.
Sub SendResponse() Dim Dim Dim Dim Dim Dim Dim Email As String Name As String Male_or_Female As String Continent As String Action As String Your_Time As String n
Email = GetSmallField("EMailAddress") Name = GetSmallField("Name") On Error Resume Next Male_or_Female = GetSmallField("Male_or_Female") On Error GoTo 0 Continent = GetSmallField("Continent") On Error GoTo Done_Decoding Do If n = 0 Then Action = "We will: " & GetSmallField("Action") Else Action = Action & " and " & GetSmallField("Action_" & n) End If n = n + 1 Loop Done_Decoding: Resume Done_Decoding1 Done_Decoding1: On Error GoTo 0 Your_Time = GetSmallField("Time") Send Send Send Send Send Send Send Send Send Send Send Send Send Send Send ("Content-type: text/html") ("") ("<HTML><HEAD><TITLE> Thanks!") ("</TITLE></HEAD>") ("Thank you for submitting your E-Mail address! <br>") ("<pre>") ("We have registered: " + Email + "<br>") (" Your Name: " + Name + "<br>") (" You are: " + Male_or_Female + "<br>") (" You live in: " + Continent + "<br>") (" Time: " + Your_Time + "<br>") (Action + "." + "<br>") ("</pre>") ("</FORM>") ("</HTML>")
End Sub
The first thing that may attract your attention is the way you decode the radio buttons:
On Error Resume Next
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 8 de 14
You previously learned that the radio button field is non-existing when not touched by the users and that the GetSmallField function generates an error on a non-existing field. Therefore, you need to use error trapping. The On Error statement traps the error and performs a task specified behind the statement. So if the following line generates an error,
Male_or_Female = GetSmallField("Male_or_Female")
the program discards this line and continues with the execution of the next line as specified in the On Error statement. The variable Male_or_Female then stays empty. The following line resets the error handler:
On Error GoTo 0
The cgi32.bas framework also contains error-handling routines, so resetting the error handler to its defaults is a good idea. The select box is decoded quite easily, similar to the normal input fields:
Continent = GetSmallField("Continent")
The check boxes are also decoded in a special way. Depending on the number of checked boxes, more or fewer Action fields are enumerated (Action, Action_1, Action_2, and so on). You can't predict how many fields there will be; the number of fields depends on the number of checked boxes. Because you've seen that decoding a non-existing field generates an error, you need to use error trapping here, too. You can construct a Do Loop in which you sequentially read Action, Action_1, Action_2, and so on until the GetSmallField() function generates an error (on a non-existing field). You then trap the error in the Done_Decoding routine. This then does a Resume call to the Done_Decoding1 routine, which restores the error handler:
On Error GoTo Done_Decoding Do If n = 0 Then Action = "We will: " & GetSmallField("Action") Else Action = Action & " and " & GetSmallField("Action_" & n) End If n = n + 1 Loop Done_Decoding: Resume Done_Decoding1 Done_Decoding1: On Error GoTo 0
This approach may seem impractical at first sight; however, it works well, and there's no other simple way to do it as reliably as this. Notice that you're constructing a phrase inside the Do Loop that contains the actions the users requested. The hidden field is read by using a normal GetSmallField() call:
Your_Time = GetSmallField("Time")
All data that has been decoded is then sent back to the user, as follows:
Send Send Send Send Send Send Send Send Send ("Thank you for submitting your E-Mail address! <br>") ("<pre>") ("We have registered: " + Email + "<br>") (" Your Name: " + Name + "<br>") (" You are: " + Male_or_Female+ "<br>") (" You live in: " + Continent + "<br>") (" Time: " + Your_Time + "<br>") (Action + "." + "<br>") ("</pre>")
You use the <pre> HTML tag to align the output properly. Now that you've finished editing the SendResponse procedure, save your project, compile it, and run it. Submitting a form of the e-mail project results in a response like the one shown in figure 21.7. Fig. 21.7 After the user fills in some fields of the form generated by the email.exe application and clicking the Submit button, this is how a response might look.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 9 de 14
The Database
First, you need a database. It should contain a few records with names, phone numbers, and e-mail addresses to illustrate how data access works with Visual Basic. In principle, you can use one of the database flavors mentioned earlier or a database for which you have an ODBC driver. In this example, I used an Access 2.0 database, but I discuss where you should alter the code for use with other databases. You can obtain the database needed for this example in two ways:
z
Copy the phone.mdb database from the CD into your server's CGI-WIN directory. You can't use the database straight from the CD because the database engine needs to be able to write to the database. Create the database using Microsoft Access. Note that you need to do this only if you can't copy the database from the CD. For purposes of this example, I'm assuming that you're using Access 2.0, although other versions of Access work similarly. Start Access. Then create a new database by opening the File menu and choosing New Database. Name the database phone.mdb and situate it in your server's CGI-WIN directory. Click the New button while the Table tab is activated and then choose New Table. A table is then created. Now add three new fields by typing the names Name, Phone_Number, and Email_Address into three separate Field Name cells. The data type needs to be Text for all fields (which is the default). Next, close the table and choose Yes after being asked to save the table. Name the table My_Table, and if you're asked for it, choose to create a primary key. Use the Open button while the Table tab is activated to open the table and start adding names, numbers, and e-mail addresses. Your database should look something like figure 21.8. At this point, you've created a database called phone.mdb, which contains the table My_Table with the text fields Name, Phone_Number, and Email_Address.
Fig. 21.8 After you've successfully created a database using Access 2.0, the results should look something like this. Now that you have your database, you can start writing the data-access application. The first part of it is similar to the e-mail application you created previously. Open Visual Basic. Then open the File menu and choose New to start a new project. If you have any forms, remove them by opening the File menu and choosing Remove File. Do the same for modules (if any). Then open the Tools menu and choose References. In the References dialog box, deselect the MS DAO 3.0 Object Library item, select the MS DAO 2.5 Object Library item, and close the dialog box. This is to ensure that VB uses the proper database engine. Add the cgi32.bas framework to your project by opening the File menu and choosing Add File. The cgi32.bas should be in your Web server's cgi-src directory. Next, add the module that contains the data-access code. Open the Insert menu and choose Module to add the module. Visual Basic names it Module1. As with the e-mail application, add an Inter_Main procedure by typing the following in the general-declarations section of Module1:
Sub Inter_Main
Then, in the general-declarations section of Module1, add the code shown in listing 21.9.
Listing 21.9 phone.vbp: The CGI_Main Procedure of phone.bas
Sub CGI_Main() If CGI_RequestMethod = "GET" Then SendReQuest Exit Sub Else SendResults Exit Sub End If End Sub
When the users access the CGI script for the first time using a GET request method, the SendReQuest procedure is executed. This procedure generates a form. When the users submit a query using the POST request method, the SendResults procedure is called; it contains the actual data access code. Next, add the SendReQuest procedure to Module1 as shown in listing 21.10.
Listing 21.10 phone.vbp: The SendRequest Procedure of phone.bas
Sub SendReQuest() Send ("Content-type: text/html") Send ("") Send ("<HTML><HEAD><TITLE>" & "Phone number database" & _ "</TITLE></HEAD>") Send ("<BODY>") Send ("<FORM METHOD=""POST"" ACTION=""/cgi-win\phone.exe"">") Send ("Fill in (a part of) a name and press Search") Send ("<br>") Send ("<br>") Send ("<INPUT SIZE=30 NAME=""query"">") Send ("<br>") Send ("<br>") Send ("<INPUT TYPE=""submit""") Send ("VALUE=""Search"">") Send ("") Send ("</FORM>") Send ("<HR>") Send ("</BODY></HTML>") End Sub
The SendReQuest procedure generates a form with a 30-character wide input field named query. Because this example is essentially the same as the e-mail example, you can quickly move on to the actual search procedure called SendResults. Enter the code shown in listing 21.11.
Listing 21.11 phone.vbp: The SendResults Procedure of phone.bas
Sub SendResults Dim Db As Database Dim tmpDyna As Dynaset Dim query As String Dim SQLQuery As String query = GetSmallField("query") Send ("Content-type: text/html") Send ("") Send ("<HTML><HEAD><TITLE>" & "Phone number database" & "</TITLE></HEAD>") Send ("<BODY>") Send ("You searched for: " & query & "<br>") Set Db = OpenDatabase("cgi-win\phone.mdb", False, True)
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 10 de 14
SQLQuery = "SELECT * FROM MY_Table WHERE Name like " & "'*" & _ query & "*'" Set tmpDyna = Db.CreateDynaset(SQLQuery) If tmpDyna.RecordCount = 0 Then Send ("Your search produced no Else Send ("Results<br><br>") Do While Not tmpDyna.EOF Send ("<PRE>") Send (" Name : " & Send (" Phone number : " & Send (" Email address : " & Send ("</pre>") Send ("<br>") tmpDyna.MoveNext Loop End If Send ("</BODY></HTML>") End Sub results.<br><br>")
Now you have all you need to search a database in Visual Basic and send back the results to the users. Simple, isn't it? Because you might want to set up your own Websearchable database, I explain all code used here. If you understand how this code works, you can adapt it for use with your own database. The SendResults routine starts with decoding the query field:
query = GetSmallField("query")
For your users' convenience, you repeat the query that has been submitted:
Send ("You searched for: " & query & "<br>")
Next, you open the database by using the Visual Basic OpenDatabase() function. It has the following syntax:
Set db = OpenDatabase(dbname[, exclusive[, read-only[, source]]])
db This is the name of an object that has been declared as a database object with a Dim statement. dbname This string contains a path or a network path to a database that Visual Basic supports directly or a name of an ODBC data source. exclusive This Boolean value determines whether the database is opened as exclusive-that is, whether other applications are allowed to open the database at the same time. In general, you should set the exclusive value to False because it allows more than one user to search your database at the same time. read-only This Boolean value determines whether the database is to be opened with read/write or read-only access. You should set this value to False unless you want
to alter the database with your CGI application. source This string contains any additional information that's needed to open the database. This information could be a logon name, a password, and so on. If you leave the dbname string empty and set the source string to "ODBC", a dialog box appears in which you can browse for a registered ODBC data source. This feature is particularly useful when you experience problems while opening a database with an ODBC driver. The documentation that comes with a particular driver should provide you more information on how to open such a database.
For this example, the following line is used to open the database:
Set Db = OpenDatabase("cgi-win\phone.mdb", False, True)
Db
Dim Db As Database
Because you situate the database phone.mdb in the server's cgi-win directory, you use the following path to it: "cgi-win\phone.mdb". If you experience problems, you should change it to the full path, which may look like the following:
"c:\website\cgi-win\phone.mdb"
The full path, of course, depends on your setup. You don't have to place the database in your server's cgi-win directory. It works as long as you supply the correct path. You can also use a database file from another PC on your network. You should specify it as follows:
"\\server\directory\database.mdb"
Notice in the example that the database is opened in non-exclusive and read-only modes. By using these modes, you allow other applications to open the database and multiple users to use your Web-searchable database concurrently. Because you're only searching and not altering the database, opening the database in read-only mode is safe. The source string is omitted in this case because the database needs no additional information to be opened. As you learned previously, you probably need to specify this string only when you're using an ODBC driver. After you open the database, you need to search for the terms that the users have submitted. You can do so in a couple of ways in Visual Basic, but here you use an SQL query.
See " Generating SQL Code to Transfer Submitted Data," for more information on SQL.
This query tells the VB database engine to select every record in table My_Table for which the Name field contains the string query.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 11 de 14
The * (asterisk) wild card before and after the query string make the database engine search for substring matches. This means that the query selects all records that contain the query string, not just the ones that exactly match it. So if you search for '*fred*', not only does the database engine select records matching Fred, but it also selects Alfred and Frederique. Similarly, you can also use ? and # as single-character and single-digit (0-9) wild cards, respectively. By default, SQL queries in VB are caseinsensitive. However, some ODBC drivers are case-sensitive.
SQL in Visual Basic varies slightly from ANSI (standard) SQL. If you're using an ODBC driver or direct ODBC.DLL API calls, you might need to use the ANSI equivalent of the wild cards mentioned here: Visual Basic SQL ANSI SQL Equivalent ? _ (underscore) * %
The single quotation mark (') has a special meaning in Visual Basic. You use it to add comments within your Visual Basic source code. Because
SQLQuery = "SELECT * FROM MY_Table WHERE Name like " & "'*" & _ query & "*'"
If you want to use your own database, you can make changes to MY_Table and Name to let the database engine search the correct table and field names. Next, the SQL query is executed by using the CreateDynaset method:
Set tmpDyna = Db.CreateDynaset(SQLQuery)
A Dynaset is a dynamic part of the database that matches the criteria of the SQL query. You first check whether the search returns anything by using the RecordCount method. If the Dynaset contains no matching records, you send a short message that the search failed:
If tmpDyna.RecordCount = 0 Then Send ("Your search produced no results.<br><br>")
If the Dynaset isn't empty, you read the Dynaset record by record by using the MoveNext method within a Do Loop. The Do Loop is aborted as soon as the end of the Dynaset is reached. This is done by reading the EOF property of the Dynaset, which is True after the last record is read:
Do While Not tmpDyna.EOF Send ("<PRE>") Send (" Name : " & tmpDyna("Name")) Send (" Phone number : " & tmpDyna("Phone_Number")) Send (" Email address : " & tmpDyna("Email_Address")) Send ("</pre>") Send ("<br>") tmpDyna.MoveNext Loop
In each cycle of the Do Loop, all three fields (Name, Phone_Number, and Email_Address) for the current record are read by calling the Dynaset tmpDyna with the name of the field as an argument. (If you use another database, you should, of course, change Name, Phone_Number, and Email_Address to the correct field names.) You're now finished with the phone Web-searchable database. To save your project, open the File menu and choose Save Project. Name your project phone.vbp and name Module1 phone.bas. Then open the File menu and choose Make EXE File to compile your project. Name your project phone.exe and place it in your server's cgi-win directory. (You can also find the project file phone.vbp and the BASIC file phone.bas on the CD-ROM that comes with this book.) Run phone.exe by pointing your Web browser to the following URL:
z
http://your.servers.address/cgi-win\phone.exe
Replace your.servers.address with the Internet address of your server; or if you run your Web browser on the same machine the Web server resides on, you can use the loopback IP number 127.0.0.1. (If your machine isn't connected to the Internet, you do need to use the loopback IP number.) Your completed Web-searchable phone number database should look something like figure 21.9 on your Web browser. Fig. 21.9 The phone.exe CGI application generates a form like this. Now type something in the field and click Search. The results of a search for the letter a are shown in figure 21.10. All names that contain an a are listed. You also can type a name such as Paul or Carl, but this example better illustrates how the application searches for substrings. Fig. 21.10 After you search for 'a' with the phone.exe application, the results should look something like this. I received the error message Couldn't find file 'cgi-win\phone.mdb'. (error #3024). What's going on? This message tells you that the path specified in the line containing the OpenDatabase statement in procedure SendResults of phone.bas is incorrect. You should change cgi-win\phone.mdb to the full path of your database. When I try to compile the phone.vbp project, a User defined type not defined error is generated. During execution of the script, an Error Loading DLL message is generated. What's happening? The references to the Visual Basic data object libraries are incorrect. Open the File menu and choose References. From the References dialog box, deselect MS DAO 3.0 Object Library and select MS DAO 2.5 Object Library. Depending on the type of database, you might need to select the Microsoft 2.5/3.0 Compatibility
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 12 de 14
library item. I've specified the correct path to the database, but the application still refuses to run. What more could be wrong? If you've specified the correct path to the database and your database application still refuses to access the database, you should make sure that the Visual Basic runtime libraries for data access have been properly installed on the server PC. Even if you know what files are needed, it's not enough to just copy them to your server's hard disk. You can, of course, install another copy of VB on the server, but there's an easier way. You can use VB's Setup Wizard to prepare installation floppies with all the libraries you need. If you select phone.vbp as the project, the Setup Wizard includes all data-access libraries, and the setup.exe file that's generated installs these libraries when executed on the server PC. If you're using an ODBC driver, make sure that you've configured it as prescribed in the documentation that's supplied with the driver. By default, Visual Basic 3 can't use the Access 2.0 database supplied on the CD-ROM because it supports only the Access 1.0 and 1.1 database formats. However, after the release of Access 2.0, Microsoft released a compatibility layer that allows Visual Basic 3 to use Access 2.0 databases. If you have access to the Internet, you can download the compatibility layer from Microsoft's Web site at this site. You can also contact your local Microsoft dealer.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 13 de 14
Visual Basic 4.
Microsoft's VBScript will be a subset of Visual Basic that's optimized for Web browsers. The Visual Basic code can be embedded within the HTML document. A small runtime library will be called by the browser when it receives a Visual Basic script. The runtime library can be licensed for free. Imagine that you're selling CDs on the Internet, and you want your forms to add up the total costs while the user is gathering acquisitions. You'll be able to add a script like the following to your form:
<Script> Sub CheckBoxLouReed.Click TotalAmount.Text = Cstr(Val(TotalAmount.Text) + 19.99) End Sub </Script>
Note that this is just an illustrative example. Even the HTML <Script> tags still have to be negotiated with the World Wide Web standards committees. The main advantage of Visual Basic Script is that it's as intuitive and easy to learn as Visual Basic. If you've done some Visual Basic programming before, you'll probably be programming Visual Basic Script in no time. JavaScript is another scripting language that's being implemented in the Netscape browser. Unlike the Java language, which is compiled at the server side, JavaScript is interpreted at the client side. Because it's object-oriented, JavaScript has more of a C++-type of approach and requires somewhat more advanced programming skills. Implementations of JavaScript for Web servers will also be available as alternatives for CGI. One ongoing discussion is how safe these scripting languages are. Could someone write a computer virus in a scripting language and erase your hard disk? The JavaScript developers have dealt with this issue beforehand by disallowing write access to your hard disk. However, I have heard reports of a JavaScript that collected and submitted the user's e-mail addresses to a server as a quick and dirty way of doing market research. Some other restrictions related to these scripting languages are in place. Suppose that you don't want to share the source code of your script with rest of the world. This is impossible with VBScript and JavaScript, because the source is sent to the user when he accesses your server; it's imbedded in the HTML document and interpreted by the user's Web browser. In the case of a script that accesses a database, you'll need to send the database along with the script, which is, of course, undesirable. These scripting languages will certainly be useful for some applications; for other applications, you'll still need to rely on CGI. Copyright notice: The Visual Basic projects in this chapter use the cgi32.bas Visual Basic CGI framework by Robert Denny, which is Copyright[cw] 1995, O'Reilly & Associates, Inc., All Rights Reserved, and is reproduced with permission of O'Reilly & Associates.
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013
Pgina 14 de 14
Previous Chapter <-- Table of Contents --> Next Chapter QUE Home Page For technical support for our books and software contact support@mcp.com Copyright 1996, Que Corporation
http://www.rigacci.org/docs/biblio/online/cgi/Cgi21fi.htm
14/02/2013