You are on page 1of 69

Criando um dialog de confirmao

1. Adicione um TIWButton no form. 2. Implemente a propriedade Confirmation do TIWButton.

3. Desta forma, s ir chamar os eventos do boto, se no Dialog o usurio confirmar.


Chamando um evento do boto com JavaScript
1. Adicione um TIWEdit e um TIWButton no form.

2. No evento OnClick do boto, digite: WebApplication.ShowMessage('teste'); 3. Na propriedade ScriptEvents do Edit, digite:

Dessa forma, quando for pressionado ENTER no Edit, ir chamar o evento onClick do Boto.

Intraweb
Por Rafael E. Guarasemini

1. O que Intraweb? Intraweb uma biblioteca de componentes de desenvolvimento de htmls de forma simples, rpida e eficiente. Este biblioteca desenvolvida pela empresa www.atozedsoftware.com que trabalha com tecnologia para Internet a 15 anos. 2. Recursos A biblioteca de componentes do Intraweb traz a maioria das ferramentas necessrias para o desenvolvimento de web pages, adicionando a facilidade de programao de ferramentas de desenvolvimento de sistemas. O Intraweb esta disponvel para vrias linguagens de programao, entre elas:
o o o o o

Borland Delphi; (ferramenta base para este documento) Borland Kylix; Microsoft Visual .net; Borland J Builder; Etc...

Os componentes fornecem desenvolvimento de sites convencionais, dinmicos, com acesso a base de dados, utilizao de CSS, animaes em geral. 3. Funcionamento O desenvolvimento de sites com o Intraweb bastante simples, seu funcionamento em um servidor de Internet tem como funcionamento detalhado na figura abaixo:

As aplicaes Intraweb, diferente do desenvolvimento tradicional de web site, gera apenas 1 arquivo, onde nele contm todo o projeto desenvolvido (com exceo base de dados e figuras). 3.1. Tipos de sistemas em Intraweb

Para se desenvolver sistemas utilizando o Intraweb necessrio saber algumas coisas, principalmente, sobre onde ficar esta aplicao, isto quer dizer, qual ser o sistema operacional e qual ser o servidor de web disponvel para se utilizar. Tendo estas respostas necessrio saber a quais sistemas operacionais e a quais servidores de web o Intraweb fornece suporte de desenvolvimento. O Intraweb oferece suporte para tais sistemas: Microsoft Windows ISS Apache Apache

Linux (utlizando o Borland Kylix)

4. Comeando a utilizar o Intraweb O Borland Delphi oferece as duas alternativas de desenvolvimento com o Intraweb citados no captulo anterior. Sendo estes encontrados em: No menu File New Other, na aba Intraweb, aqui voc seleciona o tipo de aplicao que ir desenvolver. A figura abaixo demonstra a tela para se escolher o tipo de aplicao.

4.1. Apache 2 DSO Application Desenvolvimento de aplicaes para Windows utilizando o servidor de web Apache verso 2 ou superior e se baseia no desenvolvimento de um objeto de compartilhamento dinmico. Este tipo de aplicao gera um arquivo com a extenso so (shared objetc) que deve ser configurado para ser carregado no servidor Apache nas diretrizes de Load Modules no httpd.conf (arquivo de configuraes do Apache), isso deve ser feito da seguinte maneira: o arquivo .so deve ser colocado no diretrio de Modules do Apache;

no arquivo de configuraes do Apache, localize a chave Dynamic Shared Object, neste local onde se configura os mdulos que sero carregados com o Apache;

Insira uma diretiva de LoadModule, onde deve ser colocado o nome do se arquivo .so, sendo a sintaxe a seguinte: LoadModule nome do module gravado nome do .so <Location /URL> SetHandler varivel de ponteiro do .so </Location> Onde: nome do module gravado o do projeto do Intraweb no Delphi, encontrado no dpr (Projeto) da aplicao iniciada. Existe uma varivel exportado do Delphi com o nome apache_module name. O contedo desta declarao case sensitive. Nome do .so nome do nome do arquivo gerado no final da compilao. /URL o ponto de execuo para um broswer, um exemplo seria /delphi. Esta varivel case sensitive varivel de ponteiro do .so uma varivel case sensitive onde se inclui o nome da module com o sufixo handle Para se debugar uma aplicao deste tipo, deve-se fazer os seguinte passos:

no menu Run Parameters, coloque o path do servidor Apache, como figura abaixo:

habilite no menu Tools Debugger Options a opo spawned processes Apache DSO Application

4.2.

Segue o mesmo modelo do capitulo 4.1. Apache 2 DSO Application

4.3.

Application Form

Segue o esquema de quando se esta desenvolvendo um sistema convencional no Delphi e se deseja inserir um novo Formulrio. Este cone apenas acrescenta uma nova pgina (Form) para se desenvolver. 4.4. ISAPI Application

Utiliza para desenvolver aplicaes para servidor Microsoft Windows utilizando servidores de Internet ISS. Como compilao final, gerado uma dll deve ser configurada da seguinte forma (exemplo):

Copie do arquivo ISAPITER.dll do diretrio de instalao do Delphi (bin\netscpXX) para C:\Netscape\Server\Nsapi\Examples (diretrio de instalao do servidor) No arquivo de configurao do servidor (OBJ.CONF), encontre a linha:

fn=load-types mimi-types=mimi.types e inseria a seguir Init funcs=handle-isapo, check-isapi, log-isapi fn=load-modules Shlib=c:/netscape/server/nsapi/examples/ISAPIter.dll Ainda no arquivo OBJ.CONF, encontre a seo: <Object name=default> e encontre a linha NameTrans fn=document-root root=C:/Netscape/Server/docs E inseria a seguinte diretiva: NameTrans from="/scripts" fn="pfx2dir" dir="C:/Netscape/Server/docs/scripts" name="isapi" E no fim do arquivo arquivo OBJ.CONF coloque <Object name="isapi"> PathCheck fn="check-isapi" ObjectType fn="force-type" type="magnus-internal/isapi" Service fn="handle-isapi" </Object>

No arquivo no fim do arquivo MIME.TYPES, coloque a linha

Type=magnus-internet/isapi exts=dll 4.5. Page Form

para se inserir uma nova pgina de html para se desenvolver na aplicao. 4.6. Stand Alone Application

Cria uma aplicao para testes, tem funcionamento idntico a qualquer outra aplicao com Intraweb, porm, quando permite que seja rodada na IDE do Delphi, pois, tem um servidor de web interno para se executar e debugar. Logo abaixo h uma figura com o servidor de web interno do Intraweb

4.7.

Stand Alone Application with Data Module

Funcionamento idntico ao Stand Alone Application, porm, j se inicia com um Data Module. 5. O Intraweb no Delphi

O Delphi, a partir da verso 6, dividido em duas blibliotecas de componetes, a VCL e a CLX A VCL Visual Components Library so todos os componentes do Delphi, desde o TForm ao mais sinistro TTeeChart.

A CLX - Component Library for Cross-Platform so quase todos os componentes do Delphi, so utilizados para se desenvolver uma aplicao no Delphi e prepara-la para ser recompilada no Borland Kylix no Linux. Ainda nem todos os componentes que existem na VCL existem na CLX, mas em breve ser por completo. Os componentes no so separedos em VCL e CLX, o que for VCL , tambm CLX, isso pode ser reparado no cdigo fonte dos componentes. O Intraweb no Delphi divido em 4 palhetas, cada uma dividida por categoria de componentes, desde componentes simples como o TIWLabel (o componentes TLabel da VCL) como componentes para criao de grficos dinmicos TIWDynamicChart (similar ao TDBChart da VCL). Uma caracterstica importante que os componentes do Intraweb s podem ser utilizados em aplicaes Intraweb e essas aplicaes tambm s aceitam seus prprios componentes. Um jeito de se certificar disso tentar colocar um componente da VCL/CLX em uma Intraweb Application. 5.1. Os Componentes Standard Nesta palheta esto localizados os componentes mais simples do Intraweb, pode-se notar uma similaridade com a palheta Standard do Delphi. Nela se encontrar labels, buttons, combobox, times, grids, checkbox, menu etc que so mais comuns at componentes para html em si , como link, URL, applet, flash, layers, etc. A palheta IW Standard pode ser vista na figura abaixo:

5.2.

Os Componentes Data

Nesta palheta esto localizados os componentes para controle da base de dados para qual estiver se conectando. Os componentes desta palheta so similares aos da palheta Data Controls da VCL/CLX, so componentes como DBGrid, DBLabel, DBEdit, DBNavigator e demais parecidos com a palheta da VCL/CLX. Assim como os da VCL/CLX, eles so ligados com um Dataset. Os componentes dessa palheta podem ser vistos na figura abaixo:

5.3.

Os componentes Client Side

Nesta palheta esto componentes para quem esta acessando a pgina html. So componentes para grficos e legendas dinmicas, grids dinmicos, com labels e navigators. Os componentes dessa palheta podem ser vistos na figura abaixo:

5.4.

Os componentes Control

Nesta palheta esto componentes para controle da pgina a ser exibida, contm controles para layout (templates) e produtores de pginas. H um componente (IWLayoutMgrHTML) que contm um editor html interno (basta dar um duplo click). Os componentes dessa palheta podem ser vistos na figura abaixo:

6.

Exemplos

Mostraremos agora alguns exemplos para utilizao dos componentes do Intraweb e modelos de aplicaes que servem como base para maior desenvolvimento. No h um exemplo de como se fazer links entre as pginas do Intraweb, mas a estrutura : TIwAppForm(RWebApplication.ActiveForm).Release; [nome do formulrio que se quer abrir].Create(RwebApplication).Show; 6.1. Exemplo 1

Neste primeiro exemplo, apenas mostraremos a cumplicidade da programao em Delphi e seu desenvolvimento para web.

Nada mais do que mandar escrever em um label o que foi digitado em um memo.

6.2.

Exemplo 2

Neste segundo exemplo, mostraremos os tipos de mensagens e popus que o Intraweb nos oferece. A base para as mensagens a mesma do Delphi, o conhecido showMessage, a diferena que por se trabalhar em um servidor de Internet, no existe a IDE a plataforma de suporte Win32, devemos ento mandar o servidor de web dar a mensagem, isso feito a partir da sintaxe: WebApplication.ShowMessage([texto],[tipo de mensagem],[template msg]) E como podemos ver na figura abaixo, se trata somente de um memo onde se digita o texto, um radiogroup para o tipo da mensagem e um boto para executar a mensagem.

6.3.

Exemplo 3

Neste terceiro exemplo, iremos demonstrar a utilizao de outros componentes que o Intraweb oferece.

Estes outros componentes so todos encontrados na VLC do Delphi e a sua manipulao idntica se programados em sistemas convencionais. Como podemos visualizar na figura abaixo, estamos utilizando checkbox, listbox, combobox, edit, button e shape , onde, cada um desses componentes esto referenciados a partir da VCL, para se utilizar os do Intraweb, basta colocar o prefixo IW ao nome dos componentes, com exceo do shape que no Intraweb se chama IWRectangle e inferior ao shape. Quanto a utilizao, idntica a programao com a VCL.

6.4.

Exemplo 4

Neste quarto exemplo, mostraremos como efetuar downloads a partir de uma aplicao Intraweb. Estaremos utilizando a idia de se mostrar o que pode ser feito donwload (utilizando uma rotina de SearRec em um diretrio e mostrando tudo o que tiver extenso .JPG). O boto download faz o download da figura em stream e mostra no programa para qual estiver configurado para visualizar figuras. Os componentes so os comuns do Intraweb e para se efetuar o download de algo, existe a seguinte funo: WebApplication.SendFile([arquivo],[string],[string],boolean)

6.5.

Exemplo 5

Neste quinto exemplo, iremos demonstrar como se efetuar upload a partir de uma aplicao Intraweb. Como podemos visualizar na figura abaixo, existe, visualmente, 3 componentes; porm, na verdade estamos utilizando apenas 2 componentes: um IWButton e um IWFile. O IWFile esse conjunto de caixa de texto e o boto Procurar. Esse componente parecido com o OpenDialog da VCL, ele permite voc buscar no seu hd o arquivo para se fazer upload, esse processo, ele faz sozinho. Para se efetuar o upload de um arquivo, h uma funo do componente IWFile: SaveToFile([path]) salva para o hd o arquivo escolhido Ou SaveToStream([path]) salva para uma stream (varivel de memria)

6.6.

Exemplo 6

Neste sexto exemplo, iremos ver como acessar uma nova pgina ou site para uma nova janela. Tudo se tratar apenas de uma chamada de funo que na verdade j existe no Delphi.

AddToInitProc('NewWindow(''' + Trim([URL]) + ''', ''MyWindow'', '''') Somente h um edit para se digitar a URL (tem que ter o http://) e um boto para abrir.

6.7.

Exemplo 7

Neste stimo exemplo, demonstraremos um refresh programado. Esse recurso bastante usado em chats para se atualizar o pgina para novas mensagens. Para se fazer este processo, utilizamos o componente IWTimer, que tem o funcionamento similar ao Timer da VCL, nele, programamos o tempo de intervalo (no exemplo 2 segundos) e no evento OnTimer voc pode verificar se esta ocorrendo o processo, no caso, aparece a mensagem da figura abaixo mostrando quantas vezes o html foi atualizando.

6.8.

Exemplo 8

Neste oitavo exemplo, iremos ver como utilizar Templates. Templates so htmls j formatados por algum editor de html, desde o Macromedia DreamWeaver, Microsoft FrontPage ou mesmo para os mais espertos, no bom e velho Bloco de Notas do Windows. Estes htmls podem contar qualquer tipo de layout. Para se utilizar Templates, o Intraweb fornece alguns componentes, iremos falar sobre 2 deles que so os mais fceis e comentados.

TIWTemplateProcessorHTML

Como ele, basta voc coloc-lo no formulrio Intraweb e setar a propriedade TemplateProcessor do seu formulrio.

TIWLayoutMgrHTML

Funcionado idntico ao TIWTemplateProcessorHTML, porm, ele tem includo nele um editor de html (basta dar duplo clique sobre o componente), como visto na figura abaixo:

Independente do componente que se for utilizar, existem algumas coisas que devem ser feitas para que o Template funcione:

Toda e qualquer pgina html (s pode ser html, ele no aceita htm), tem que ser salva em uma pasta chamada Templates que deve ser criada no mesmo nvel que esta a sua aplicao; Se voc criar um html, coloc-lo na pasta Templates e no seu formulrio Intraweb que vai utilizar este Template voc colocar um boto e logo em seguida rodar a sua aplicao, acessar a pgina que voc acabou de fazer....o que voc ter ?

Voc ir ver somente o seu html, nada dos componentes que voc colocou que so do Intraweb. Para que seja possvel acessar os componentes do Intraweb, necessrio utilizar os tags dos componentes no html. Veja seqncia abaixo:

Formulrio no Delphi, h somente um IWText, um IWButton e um componente para utilizao de Template

Este a visualizao do html com o sistema rodando, perceba que os componentes visuais do Intraweb (IWText e IWButton) no aparecem

J nesta figura, colocamos no cdigo html as tags dos componentes Intraweb, o que nada mais do que seguir a sintaxe: {% [nome do componente] %}, como visto na parte sublinhada da figura

Agora, quando voc rodar novamente a aplicao, os componentes do Intraweb estaro acessveis. 6.9. Exemplo 9

Neste nono exemplo, demonstraremos a utilizao de grficos estticos e dinmicos. A utilizao de qualquer de um dos tipos de grficos e bastante simples, somente necessrio saber utilizar o componente IWClientSideDatasetDBLink ou IWClientSideDataset onde se pode ligar com um DataSet (IWClientSideDatasetDBLink ) ou inserir os registro manualmente (IWClientSideDataset). O componente responsvel pela gerao do grfico o IWDynamicChart e opcionalmente pode se utilizar legendas com o componente IWDynamicChartLegend.

Nesta figura, estamos demonstrando um grfico esttico, onde somente setamos no componente do grfico qual ser a coluna e a linha

Nesta figura, o grfico gerado dinamicamente, existe 2 combobox onde se seleciona qual ser os campos na vertical e horizontal 6.10. Exemplo 10 Neste dcimo exemplo, demonstraremos como se gerar grades (grids) estaticamente e dinamicamente. A utilizao dos grid esttico feita a partir de um DataSet ligado ao componente IWDBGrid que tem a sua utilizao idntica ao DBGrid da VLC.

A utilizao de grid dinmico feita a partir de um DataSet ligado ao componente IWDynGrid, onde j ser gerado um grid com filtros e ordem automaticamente.

Aqui demonstrado um grid esttico com os registro de uma tabela, no caso, um arquivo xml

Aqui demonstrado um grid dinmico onde existe filtros e ordem dinamicamente montados 6.11. Exemplo 11 Neste dcimo primeiro exemplo, mostraremos como utilizar menus no Intraweb.

Assim como em uma aplicao normal com o MainMenu da VLC, voc somente necessita colocar um IWMenu e liga-lo com o formulrio do Intraweb, porm, h uma necessidade de se colocar tambm um TMainMenu da VCL, pois o componente do Intraweb utiliza como base ele. Para isso, basta colocar um TMainMenu no formulrio Intraweb, montar a estrutura de menus. liga-lo com o IWMenu e pronto. A estrutura de menus feita no TMainMenu estar disponvel no IWMenu. O funcionamento pode ser visto na figura abaixo:

6.12. Exemplo 12 Neste dcimo segundo exemplo, demonstraremos como se fazer um formulrio de insero de dados. O layout dos campos para se entrar com os dados, pode se utilizar IWEdits ou IWDbEdits, no exemplo, utilizamos IWEdits e IWComboBox. A montagem idntica de quando se faz um formulrio de insero para aplicaes normais, e a maneira de se fazer a insero pode ser escolhida pelo programador, voc pode dar um comando SQL de insert ou utilizar um Post ou ate mesmo, como no exemplo, um InsertRecord direto. Toda e qualquer tipo de controle que necessrio se fazer em aplicaes comuns, so feitas da mesma maneira.

7.

Concluses finais

Como visto em todo este documento, a utilizao do Intraweb algo bastante simples, principalmente pelo motivo de se programar da mesma maneira que se programa em aplicaes normais, ganhando em rapidez e eficincia, pois estar aproveitando tudo o que a ferramenta Borland Delphi oferece para programao. 8.

Bibliografia
http://www.blong.com http://www.drbob42.com http://bdn.borland.com

Clique aqui e faa download dos exemplos utilizados nesse artigo.

Sobre o Autor

Rafael E. Guarasemini - ltimo ano de Bacharel de Sistemas de Informao pela


Faculdade Claretianas de Rio Claro.

Programador Delphi a 5 anos e membro do NUPEDS (Ncleo de Pesquisa e Desenvolvimento de Sistemas da Faculdade Claretianas
COMENTRIOS

Csar Nascimento - 30/05/2003 - 13:42:11

Cara, peguei um sistema de instalao desenvolvido por voc que nunca tinha vista antes to eficiente e amigvel. voc muito bom nota 1000000000 (Gostaria de saber um pouco do que voc sabe...) ................................................
LM - 02/06/2003 - 21:22:06

Estou com uma dificuldade, uma dll que executa uma consulta est disponibilizada num IIS, de duas mquinas diferentes envio determinada consulta diferente de cada maquina e ao dar enter ao mesmo tempo, retorna a mesma consulta nas duas mquinas mesmo sendo consulta diferente. como posso solucionar esse problema? agradeo se puder me ajudar ................................................
Rafael E. Guarasemin - 05/06/2003 - 12:15:01

LM, mande uma email para mim, assim fica mais facil de conversarmos. guarasemin@horizon.com.br []s ................................................
Marcos P. Gomes - 09/06/2003 - 16:57:53

Vamos centralizar as dvidas na lista-delphi@yahoogrupos.com.br esse espao apenas para comentrios gerais sobre o material acima. Atenciosamente Marcos P. Gomes Moderador ................................................
samuel marques - 17/06/2003 - 12:54:47

eu gostaria desaber como c coloca isto realmente pra funcionar na Net, existe algum comando especifico. estou com duvidas!!! Obrigados desde j. gostei muitos de seus exemplos de WEB ................................................
Rafael E. Guarasemin - 19/06/2003 - 11:21:22

O programa stand alone, no d para vc publica-lo diretamente, vc pode baixar um programa na community do Guinther que transforma aplicaes stand alone para os dll ou apache. ................................................
Felipe Rodrigues - 25/06/2003 - 14:46:21

Gostei muito do seu artigo, inclusive eu tenho alguns projetos em mente, para desenvolver nesse tipo de plataforma. Gostaria de saber mais detalhes sobre como desenvolver essa relao entre o form da pgina e o DataBase.

................................................
P/ Felipe Rodrigues - 03/07/2003 - 13:22:15

Vc poderia entrar em contato por email para conversarmos sobre isso ................................................
Valmor - 07/07/2003 - 08:23:52

Gostaria de saber, como obtenho o programa que transforma aplicaes stand alone para dll, qual o endereo da community do Guinther ................................................
Ronaldo S. Vieira - 22/07/2003 - 12:03:49

Estou desenvolvendo um aplicativo usando o IntraWeb, agora esbarrei num probleminha ... Como fazer relatorio usando IntraWeb ? Se alguem souber, por favor de um toque. grato Ronaldo. ................................................
Marcelo - 22/07/2003 - 16:27:21

Caro Raphael, Primeiramente quero parabeniz-lo pelo artigo de intraweb escrito no delphibr. Bem gostaria de uma orientao, como fao para migrar um sistema inteiro feito em delphi 5 para web usando delphi 7 se possvel, me falaram sobre usas xml, mas tenho nem noo por onde comear por isso, gostaria de saber como devo comear o pelo menos onde poderia procurar algo a respeito. Desde j agradeo ................................................
P/ as pessoas q esta - 24/07/2003 - 22:18:31

olha... reparei q algumas pessoas estaum com duvida sobre como desenvolver no iw ou migra sistemas para esse modelo. qq coisa, fiquem avontade de me enviarem um email (esta no meu nome do inicio do tutorial) q farei o possivel para ajuda-los. obrigado e []s ................................................
Laercio Guero Rodri - 27/07/2003 - 11:53:17

DEPOIMENTO Aqui em nossa empres, nosso grupo de trabalho j avanou bastante em IntraWeb. J contamos com trs aplicativos usando esta tecnologia, inclusive,

uma delas atende a negcio pela internet onde nosso cliente tendo com clientes trs bancos. sem dvida uma alternativa excelente. Estamos a disposio para suporte, j que contamos tambm com um curso de treinamento especializado. laercio@digirio.com.br ................................................
Norival Hbner - 28/07/2003 - 09:16:17

Parabens pelo artigo. Est de excelente qualidade. Apoveitando a oportunidade, gostaria de saber se as Aplicaes Intraweb desenvolvidas com do Delphi 7 Enterprise precisam ser licenciadas. desde j obrigado. Norival Hbner norival@hubner.eti.br ................................................
Marcio Roberto - 02/08/2003 - 19:49:25

Parabens por esta materia, foi muito util e gostaria de saber aonde posso dirar maior duvidas sobre este assunto valeu. ................................................
Ligia torres lima - 05/08/2003 - 10:19:07

Parabns pro este artigo! tenho algumas aplicaes em delphi e gostaria de utilizar esta ferramenta. Gostaria de obter mais informaes a respeito o uso do intraweb com delphi 7. Obrigada. ................................................
Envie seu comentrio Nome Comentrios

Delphi 7 - WEB Services com IntraWEB Por Danilo Bertholini

Duas tecnologias que chamaram ateno no Delphi 7 foram os web services e o novo framework para desenvolvimento RAD para WEB o IntraWEB, nesta matria verermos como utilizar estas duas tecnologias em conjunto para criar um cliente web service. Como exemplo utilizaremos o famoso servio de traduo BabelFish, para voc que no viu as duas matrias de minha autoria sobre o assunto veja a primeira clicando aqui e a segunda aqui. Vamos ao desenvolvimento! Para iniciarmos o desenvolvimento, no Delphi crie uma nova aplicao IntraWEB do tipo Stand Alone Application adicione ao formulrio principal (FormMain) os seguintes componentes: IWEdit, IWButton, IWLabel - Todos localizados na guia IWStandard. HTTPRIO - Localizado na guia WEB Services. Posicione-os de acordo com a figura1.

Figura 1 - o Formulrio principal. Agora com o design de nosso exemplo pronto, vamos importar o servio WEB para isso v em File | New | Other na guia WEB Services selecione a opo WSDL Importer, na prxima janela digite no campo o endereo do WSDL: http://www.xmethods.net/sd/2001/BabelFishService.wsdl feito isso s seguir na importao do servio, veja no primeiro artigo da srie "crie seu tradutor" passo-a-passo como importar um servio. Com nosso servio importado vamos configurar o Server Controller, para isso pressione Shift+F12 e o selecione. Em sua propriedade ComInitialization altere para ciMultiThreaded veja na figura 2 o Object Inspector.

Figura 2 - A configurao do Server Controller. Volte ao formulrio principal "FormMain" e selecione o componente HTTPRIO1 e o configure de acordo com o quadro abaixo: WSDLLocation - http://www.xmethods.net/sd/2001/BabelFishService.wsdl Service - BabelFishPort Port - BabelFishPort Pronto, Nosso HTTPRIO foi configurado! Agora pressione ALT+F11 para utilizar a Unit do servio importado e no evento onclick do IWButton digite as seguintes linhas de cdigos: var // Declara uma referncia interface do servio, // criada pelo wizard na importao. ws : BabelFishPortType; begin // Inicializa o servio. ws := HTTPRIO1 as BabelFishPortType; // Invoca o servio e passa ao IWlabel os resultado. IWLabel1.Caption := ws.BabelFish('pt_en',IWedit1.Text); end; Agora s executar nossa aplicao! E logo a tela do Servidor Stand Alone se abre, pressione F9 novamente que o navegador executado, veja nas 3 figuras abaixo o exemplo em execuo.

Figura 3 - O Servidor Stand Alone

Figura 4 - A aplicao em execuo.

Figura 5 - A mensagem traduzida.

Para fazer o download deste exemplo clique aqui!

IntraWeb Component Evaluations


Evaluations of the following components are distributed with IntraWeb. To install, make sure to select Arcana Components when installing Intraweb.

IntraWeb Dialogs Pack IntraWeb Control Pack IntraWeb Translator IntraWeb OpenSource Pack

Other Related Downloads:

Filename IntraWeb OpenSource Pack IW 5 & 6 - ArcIWOpenSource6.zip


Final release for IW5 and IW6. Support for IW4 has been removed.

File Size Last Updated 55597 91955


5/24/2003

IntraWeb OpenSource Pack - ArcIWOpenSource.zip

2/9/2003

The latest updates to the IW OpenSource Pack. Includes source for IW 5.x and demos for 5.0.x.

Apache Shared Modules in Delphi


Brian Long (www.blong.com) Introduction Choosing Apache 1 or Apache 2 Installing Apache Controlling Apache Writing A Shared Module Using The Shared Module Debugging Shared Modules About Brian Long

Introduction
Back in Issue 69 (May, 2001) of The Delphi Magazine in Apache Shared Modules, I looked at the Apache Web server running on Linux and how Kylix could be used to write CGI applications and also Apache shared modules or DSOs (the main thrust of the article). That was shortly after Kylix had been released, and discussed how to overcome a variety of problems, including the fact that the standard Apache binary distribution is not suitable for using shared modules.

This update looks at what issues need to borne in mind when using Delphi 6 to create Web applications for Apache running on Windows. Fortunately, things are a bit simpler here than they are in Linux (a welcome relief). This article should be considered an update to the original article rather than standalone, so if you are unfamiliar with Apache and DSOs (or shared modules) I recommend you have a read of it. Just ignore any references to Linux issues along the way, particularly about recompiling Apache (there is no need to do this with the Windows version of Apache). Your first question might be to ask why we should bother looking at Apache anyway. After all, Apache on Windows is certainly not as well established as Apache on Linux, or IIS on Windows. Well, you should consider that whilst Windows 2000 Professional ships with a copy of IIS, it only has a 10 user limit. If you want your Web server to work well you will need to upgrade to Windows 2000 Server and get the appropriate additional licensing. More things in Apache's favour include the fact that it is completely free and has its full source code freely available for download. Additionally, it is straightforward to configure through one textual configuration file and has updates made to its source code tree far more frequently than IIS. On top of this, the main source code base is evidently well established, given the mass acceptance of Apache on Internet servers (primarily Unix systems), and the documentation states that it can even load up ISAPI DLLs. There is also the fact that the basic logic you place in a WebBroker or WebSnap application is much the same no matter what Web server protocol you are targeting, so you can easily target Apache Web server from your existing Web server applications by creating a new project file set up appropriately. A minimal amount of work can result in another Web server platform that you can say that you target. Additionally, it is just at home on Windows 95, 98 or Me as it is under Windows NT or 2000, so can be used for non-sensitive Web servers on a company Intranet. If you need to test Apache out (because you are thinking of setting up a Linux Web server, for example), trying it out under Windows can be much more comfortable if you are new to Linux. Get the hang of what's required of Apache in Windows, then that is one problem out of the way when you set up your Linux box. Anyway, the bottom line is that it provides another option on top of Microsoft's IIS or PWS, or Netscape server, or CGI applications, so it can be useful to know how to take advantage of it.

Choosing Apache 1 or Apache 2


Apache 2 was released after Delphi 6 and introduces some important issues. The Apache 2 module format differs from the Apache 1 module format and as a consequence, Delphi 6 can only work with Apache 1.x. To build shared modules for Apache 2 requires Delphi 7, which introduces additional support for Apache 2.x. The key difference in an Apache 2.x shared module, when compared with an Apache 1.x shared module is the project file uses clause. Shared modules targeting Apache 1.x use the ApacheApp.pas unit, whereas Apache 2.x projects use ApacheTwoApp.pas.

Note: Delphi 7 has only been certified for use with Apache up to version 2.0.39 as that was the most current version available when it was sent to manufacturing. Apache 2.0.40 introduces more changes that break the Delphi support and requiring modifications to the support units. However, all is not lost as unofficial patch information supplied by a Borland engineer is available online that allows Apache 2.0.40 and higher to be used with shared modules written in Delphi.

Figure 1: Delphi 7 Apache support Kylix 3 was released just before Delphi 7 (indeed Delphi 7 includes a copy of the Delphi language version of Kylix 3 in the box), but Apache 2 support did not make it into that product. This may happen with an update pack, but in the meantime you could always try "borrowing" the pertinent Apache 2 source files from your copy of Delphi 7 and using those instead of the Apache 1 files in your shared module project. The Apache source files are located in $(DELPHI)\Source\Internet, where $(DELPHI) is the main Delphi installation directory. The units used in Apache 1 applications are: ApacheApp.pas, used in the project source ApacheHTTP.pas, used by ApacheApp HTTPD.pas, used by ApacheApp and ApacheHTTP

The files used in Apache 2 applications are: ApacheTwoApp.pas, used in the project source ApacheTwoHTTP.pas, used by ApacheTwoApp HTTPD2.pas, used by ApacheTwoApp and ApacheTwoHTTP

So in theory you could copy the Apache 2 support files across to your project directory and modify the project uses clause to use ApacheTwoApp instead of ApacheApp. Note: that this suggestion is speculative - I haven't tested it.

Installing Apache
Before writing any Apache shared modules, you need to get hold of Apache and install it. You can get a ZIP file containing the source code from httpd.apache.org/dist/httpd, but that requires you to have Visual C++ to compile it. Instead, I recommend you get the precompiled version without source code from httpd.apache.org/dist/httpd/binaries/win32. I downloaded version 1.3.20, apache_1.3.20-win32-no_src-r2.msi, which is a Windows Installer file that can be used to install Apache. Clearly this means you need the Windows Installer on your machine, but if you haven't you can download it from the Microsoft Web site. The last time I checked there were two main versions of Apache available, one is a version 1.x (Apache 1.3.26) and one is a version 2.x (Apache 2.0.40). As discussed earlier, if you are using Delphi 6 you must download the 1.x version as support for 2.x only arrives in Delphi 7. Before installing, you should terminate any other Web servers you have running (I had IIS running on Windows 2000), as they will typically all fight for the same default TCP port (port 80). I suspended IIS through the Internet Information Services Control Panel applet (in Control Panel's Administrative Tools folder). When you run the file, the installation wizard will start:

Figure 2: Installing Apache for Windows When it gets around to asking you about your Web server information, you will be best placed to answer the questions. Since I want to access my Web server by specifying its machine name (Cube), that's what I tell the installation program:

Figure 3: Specifying my Web server settings This will mean I can browse to http://Cube from anywhere on my network and gain access to Cube's Web server. Notice in Figure 3 that the installation asks if you wish Apache to run as a service. On Windows NT/2000, this will be a good choice for a production system, as it keeps Apache running from boot-up to shutdown, but is not recommended on Windows 9x, as it is still at an experimental stage on these platforms. On a development system (and on Windows 9x), you might find it easier to choose the other option, which installs it for manual invocation in a console window. This option makes it straightforward to debug your Apache shared modules and is the recommended option when installing on Windows 9x.

Controlling Apache
When installation is done, about 4Mb of disk space will have been consumed (even though the installation program suggests it will take about 15Mb) and Apache should be ready for use. Depending whether you chose to install Apache as a service or not, your Apache Start menu folder will be organised differently. Figure 4 shows the menu structure for the service installation.

Figure 4: The Apache service Start Menu Group If you chose the other option (manually starting Apache in Figure 3), the C menu will o not be present, but you will have one extra menu item under A which says Sar , h .ph t ic Ce A n ta e l o If you installed Apache as a service, it will be running each time you start Windows. You can stop Apache with the S t menu item and start it with the Sat item. The Rs t r item will e t attempt to stop Apache if it is running, and then start it again. This is a convenient way of getting Apache to re-read its configuration file, after you have made changes to it. If Apache is installed for manual invocation, the Sa Ac i rt will start the Apache process in a Ch pe n item t e l o s n o console window (in Apache 1.3.4 and earlier, this option was called Aar ).rThis process can Se pc v h e be terminated by pressing Ctrl+C in the console window (in version 1.3.13 and later) or by clicking the console window's cross button (in version 1.3.15 and later). For both installation types, you can also terminate Apache by passing it appropriate command-line switches (it might be convenient to add a new shortcut with this command line to the Apache Start menu folder, if you installed it for manual invocation): C:\Program Files\Apache Group\Apache\Apache.exe -k shutdown When Apache is running, you can invoke your Web server's home page, with http://localhost, and you should get the default Apache home page:

Figure 5: The default Apache homepage

Writing a Shared Module


To create a shared module in Delphi 6, choose N then choose A In the Web Server | O ,e F i .p W Application wizard, choose Aac press O This creates a DLL-based WebBroker S re M ah he od and p . application, where we need to focus on the project file (choose Project | View Sour ). Note: Delphi 7 and later will give you a choice of Apache versions to target, which affects the Apache support unit used in the project source file. The default content of the project file looks like:

library Project1; uses WebBroker, ApacheApp, //or ApacheTwoApp

Unit1 in 'Unit1.pas' {WebModule1: TWebModule}; {$R *.res} exports apache_module name 'Project1_module'; begin Application.Initialize; Application.CreateForm(TWebModule1, WebModule1); Application.Run; end. In this case, I saved the project as ApacheTest.dpr, which will generate a binary file called ApacheTest.dll. To keep things consistent with the modules supplied with Apache, I added the compiler directives below to the project file to change the output name to mod_ApacheTest.so instead (so is the file extension of DLL equivalents on Linux, called shared objects).

{$E so} //change binary file extension from .dll to .so {$LIBPREFIX 'mod_'} //prefix binary file name with mod_ Note: you can also use the Application page of the project options dialog to change the extension and prefix. The other change here was to update the default exported module record name from Po ,rresulting in:

library ApacheTest; uses WebBroker, ApacheApp, //or ApacheTwoApp ApacheTestU in 'ApacheTestU.pas' {WebModule1: TWebModule}; {$R *.res} {$E so} {$LIBPREFIX 'mod_'} exports apache_module name 'ApacheTest_module'; begin Application.Initialize; Application.CreateForm(TWebModule1, WebModule1); Application.Run; end. At this point, the application can have functionality added to it, as in any other WebBroker project. In my sample shared module I have a Web action set up on the Web module (double-click the Web module or use the property editor for the Actions

property) that has no PathInfo, but sends a simple piece of HTML back in itsOnAction event handler.

procedure TWebModule1.WebModule1WebActionItem1Action(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); begin Response.Content := '<H1>Hello World</H1>' end; This should suffice to prove whether we can get a DSO working or not.

Using The Shared Module


The next step is to compile the project into the correct directory, and tell Apache to use it. In the project options dialog, the Directories/Conditionals page specifies where the compiled executable will be placed (the Output directory: option). Set this to wherever Apache stores its shared modules, which, on a default setup, is C:\Program Files\Apache Group\Apache\modules. Now compile the project (Cr+ the shared )tand l F module will take its place alongside all the default ones. The final step is to modify the configuration file. One of the menu items in the Configure Apache Server group will bring up the configuration file in Notepad. Scroll down to the commented section entitled Dynamic Shared Object (DSO) Support. In this section, you will see a number of commented LoadModule directives to which we need to add another. We also need to add a Location directive to identify which URLs will invoke the shared module. For example, you may wish all requested URLs that start with /e be handled by your shared module. to d l This is the generic template for what needs to go in the config file:

LoadModule module_record_name library_name <Location /URL> SetHandler content_type </Location> The bits you customise are: m the symbol exported by the project file and is case-sensitive. In Listing 2 you o is can see this is ApacheTest_modul e l taken from the M i is o variable (from the ApacheApp unit) and defaults to the name of the shared module binary file, with any relative path needed to access it. In my example, this will be modules/mod_ApacheTe t.so s U the case-sensitive URL portion that identifies what URLs should be serviced R is by the shared module. For the example, this will be /e d l c taken from the case-insensitive C o is o variable and defaults to a lowercase string that includes the module name without the extension, with appended. In my example, this is mn h o a d l e r

If we plug these bits into the framework above, we get this:

LoadModule ApacheTest_module modules/mod_ApacheTest.so <Location /delphi> SetHandler mod_apachetest-handler </Location> Add these LoadModule and Lc directives to the configuration file and then save it. o a Note: just before restarting Apache you should be aware of the ClearModuleList directive. If this is present in the configuration file you should ensure it occurs before your LoadModule directives, as it unloads both statically linked modules and also dynamically loaded modules (shared modules). Now you can restart Apache (as described earlier) and you will be able to browse to http://localhost/delphi. The Web server application will respond accordingly with the simple HTML string:

Figure 6: A shared module in action Note: since the URL portion of the Lc directive is case-sensitive, browsing to o a http://localhost/Delphi will give an error 404, page not found error.

Debugging Shared Modules


In order to debug a shared module, you must ensure Apache is not running. If Apache is installed as a service, stop its execution with the appropriate menu item. If Apache was installed for manual invocation, make sure it is not running in any console windows. Since your shared module is loaded by Apache when it starts, you must tell Delphi about this host application. In the Run | Parameters... path to Apache in the HA dialog, enter the full field: pp o s t

Figure 7: Telling Delphi how to debug your shared module Now go to the debugger options dialog (Tb )|u o D and enable the Dad e o sb pw pn rug checkbox. ee Now you can set breakpoints in your shared module code as you would in any normal application (although to be honest, I could only get this operational under Windows 2000; my Windows 98 tests proved unsuccessful). When you press the Run button (or ), F Delphi launches Apache, which then loads up the shared module allowing it to be 9 debugged. When you are finished debugging, remember to terminate Apache in the correct manner, as described earlier. In other words, do not simply reset the debugged process (Cr Apache may not shut down properly. Either use the Sa )tas l menu item (if t r available) or the corresponding command-line or, if Apache is running in a console window, press Cr+that window. inC t l

About Brian Long


Brian Long used to work at Borland UK, performing a number of duties including Technical Support on all the programming tools. Since leaving in 1995, Brian has been providing training and consultancy services to the Delphi and C++Builder communities, and the newly forming Kylix community. If you need training in these products, or need solutions to problems you have with them, please get in touch, or visit Brian's Web site. Since leaving Borland in 1995 Brian has been providing training and consultancy services to the Delphi and C++Builder communities. Besides authoring a Borland Pascal problem-solving book published in 1994, Brian is now a regular columnist in The Delphi Magazine and has had numerous articles published in Computing, Delphi Developer's Journal, Linux Format, Developers Review and EXE Magazine. In his spare time (and waiting for his C++ programs to compile) Brian has learnt the art of juggling and making inflatable origami paper frogs.

Download TeeChart Pro 6 for Intraweb components. (13KB) Intraweb v.5.1 For Delphi 7:
Download

Intraweb v.5.0 For Delphi 7:


Download

Download TeeChart Pro 5 for Intraweb components. (8KB) Intraweb v.5.0 For Delphi 7: Download For Delphi 6: For Delphi 5 and other: Download Intraweb v.3.5.0 For Delphi 6: Download For Delphi 5 and other:

Download

Download

Run Live demo ! TreeTree and Intraweb

IntraWeb Tutorial - Implementing a "Hello World" application


Author: Atozed Software Homepage: http://www.atozedsoftware.com

Welcome!
Hello and welcome to the exciting world of IntraWeb. In this tutorial you'll see in a few simple steps how to create and execute an IntraWeb application

Prerequisites
To run the example in this tutorial you'll need the following: IntraWeb 5.1 in Application Mode (to get an evaluation copy of IntraWeb, please go to the Atozed Software website - http://www.atozedsoftware.com) One of the following : Delphi (5, 6 or 7), Kylix (2 or 3), C++ Builder (5 or 6) or JBuilder. Visual Studio.NET is currently under development Approximately 20 minutes of your time (installation time not included)

Creating a new application

his application is built using IntraWeb Borland Edition and application mode. The first step is to create a new IntraWeb application. To do this select the File menu, then New (Select New, not New Application, etc), then Other. A "New Items" dialog will appear. Select the "IntraWeb" tab. It should look like this:

IntraWeb New Dialog

Using this dialog you can start a new IntraWeb application or add new IntraWeb forms to your existing applications. After selecting "IntraWeb Application Wizard", the wizard will launch and you'll be presented with

the following dialog:

The IntraWeb Application Wizard

For this application we'll select "StandAlone Application". This will produce a self contained executable, that will be the only thing on the server side that you'll need to run your application. You do not need a web server of any kind. Notice the other available options: you could make your application a Windows service, and ISAPI extensions for web servers that support ISAPI, like IIS and OmniHTTPD, and even an Apache module. The options in the right panel specify whether the application should have a DataModule by default, if support for user sessions will be available, whether the HTML output should be 3.2 or 4.0 (default is 4.0 unless you check the "Create Main form as 3.2" box) and if the ISAPIThreadPool unit should be used (for the IIS server only). Each new IntraWeb application consists of three modules: 1. Project1.dpr - This is the project file. 2. Unit1.pas and IWUnit.dfm - This is the main form of your application. You can change this by editing the project file, or even have multiple main forms determined by an incoming HTTP variable. 3. ServerController.pas and ServerController.dfm - This is the server controller and used to configure your IntraWeb application and create application level events. In a new application you

can leave all properties as default. If you want, you can rename any of the files by doing a Save As from the File menu.
Implementing "Hello World"

If you have worked with other web technologies you are probably gearing up for a very big tutorial on simply how to implement even the simplistic "Hello World". I hope we will not disappoint you, but this tutorial will be very short, but only because IntraWeb makes this so amazingly simple. Open the main form of the application (Unit1). It will appear as a blank form like this: Blank IntraWeb Form

You will quickly notice the form is blank. Do not worry - this is just like a new normal Delphi application when we create it. The main form is blank and we must implement our application. Select the IntraWeb standard components tab (IW Standard tab) on the component palette as shown here:

IntraWeb Standard Palette

In the standard palette you'll see the base components for web development. However, that's not all. You an look in the other IntraWeb palettes to see components for database access, HTML 3.2 output, client side processing etc. For a complete reference of IntraWeb components, please see the IntraWeb Reference file. You can download this file from the Atozed Software website. Select the TIWLabel and then place it on the form. It should look something like this:

Main form with label

Now just like a normal Delphi application use the property inspector to change the caption of the label. Change the caption to "Hello World Wide Web!". You will notice that the label on the form

updates itself to reflect this change:

Caption of the label has changed

Now all that is left to do is to run the application and test it.
Running the application

We have created this application as a stand alone application. What this means is that it will execute completely stand alone and become its own web server. This is extremely useful for debugging and testing, but it can also be deployed in this manner. Not only can it run stand alone, but it can be installed as a service on Windows NT, Windows 2000 and Windows XP. Please see the IntraWeb documentation for more information on this. To test our application, simply run it as you would any other Delphi application. You will then see a dialog similar to this:

IntraWeb Stand Alone Information Dialog

This is a dialog to assist you in testing and debugging. To test it in the browser click Run then Execute or press the F9 key. This will launch your default browser with the start URL for the application:

The browser window

Conclusion

Congratulations! You have just created a web application! All of this with no HTML, and it was just like a normal Delphi application was it not? Now you might say "Well that is fine and dandy, but what about input? You are just showing us limited pieces and there are hidden gotchas." Trust me, there are no such "gotchas" waiting for you. IntraWeb handles input just like any other Delphi application. Want to handle a button? Define the OnClick event, that is it. Want to read the value of a text box? Read its text property. But please, do not simply take our word for it: See the next tutorial - User Input. Download the fully functional evaluation edition and look at the demos.

IntraWeb Tutorial - User Input


Author: Atozed Software Homepage: http://www.atozedsoftware.com

Introduction
In this tutorial you'll learn how to use multiple forms, how to handle user input and how to use sessions. In order to understand and run the example in this tutorial you should read the "Hello World" tutorial first.

What is Next
This application is built using IntraWeb's application mode. The last tutorial was very basic and designed to simply show you how easy it is to get an IntraWeb application up and running. As you will soon see the code used is still standard Delphi code. We challenge you to try even something this simple with any other web development tool. Other development tools require you to set up adaptors, bindings, or handle the HTTP variables your self. Not IntraWeb, IntraWeb is truly componentized. For this demo, we will continue by modifiying our "Hello World" application built in the Hello World demo. If you have not created this project yet, you will need it for this demo.

Changes to the Main Form


Set the form's Title property to "What is your name?". This will be displayed as the page title when shown in the browser. Change the label's Caption to read "What is your name?" Add a TIWEdit to the form. Set the Text property to be blank. Set the Name property to editName. Add a TIWButton to the form. Set the Caption property to "Talk to me!".

Your form should now look something like this: New Main Form

Handling a Button Click If you have never worked with web development tools before, this next step will not seem like magic for you as you will think, "This is the way it should work, no?". However if you have worked with other web development tools, you will now really begin to see where IntraWeb is different. To handle a button click in IntraWeb, it is just like a normal Delphi application. Simply create a OnClick event for your button and add code. To do this, double click on the button. Delphi will create a shell event for you similar to this:

Add the following code to the event:

Testing the Application Run the application as we did in the previous demo, and press F9 again after the debug window appears to launch the browser. The browser should appear like this:

In Internet Explorer

Notice the browser has picked up on the page title as set in the form's title property. Enter your name in the edit box and press the button. The browser will respond like this:

Hello !

Special Notes
Netscape Users Please see "Why when debugging using the IDE and Netscape 4 is the application is slow on the development machine and the task manager shows 100%?" in the FAQ. Internet Explorer Users Please see "When when using Internet Explorer is there a delay when I first click on a button?" in the FAQ. Farmers Please see "Why did the chicken cross the road?" in the FAQ.

Code Examination
Wow! That was pretty cool eh? Yes, but the really cool part was that it was done purely with standard Delphi code. We still have not written a single line of HTML or Javascript, and this is exactly how IntraWeb works. Let's take a look again at the code we wrote to do this and examine it line by line.

Wc st od E! OW ds wd al ce bo tf hi Ttn /no O n a i lr hi t e u

f n e o /

Multiple Forms ust to show you that there are no hidden gotchas with IntraWeb, let's continue on and show you how easy it is to do multiple forms with IntraWeb. Select New | Other from the File menu, and select the IntraWeb tab. This time select New Form and click OK: Creating a New IntraWeb Form

The following dialog will appear, allowing you to select the form type:

New Form Wizard

This dialog allows you to select whether you want a Page Mode form, or an Application Mode form. For each of those, the HTML type is also selectable, so you can chose to produce a HTML 3.2 form or a HTML 4.0 form. For this tutorial we'll chose "Application Form", which will produce a HTML 4.0 application mode form. For a detailed explanation of page mode and application mode, please refer

to the IntraWeb Manual. You will now have a new blank form again: New Blank Form

Using the property inspector, apply the following changes: Change the form Name property to formHello. Add a TIWLabel Set the Name property to lablHello. For the Font property: Bold = True Size = 24 Name = Arial Narrow Color = clRed

AutoSize = False. We will be adjusting the text at run time and thus will be manually

adjusting the width. Width = 300 Add a TIWLink Set the Caption property to Close. Create an OnClick event by double clicking on the TIWLink. Add the following statement to the event:

Your form should now look something like this:

Now let's move back to our main form. Change the button click event to read as follows:

Let's also add one more TIWButton to the main form. Set its caption to Done, and create an OnClick event to read:

Now run the application and press F9 when the debug window appears. The browser should appear similar to this:

Enter your name and click the Talk to Me! button. The browser now displays your second form like this:

Notice that even the browser caption has been updated with your name. Click the Close link. The browser will return to your main form:

Now click the Done button. The browser will terminate the application and display this message:

Wow! Multiple forms, transparent user input, automatic session management, the works! And we still have not written a single line of HTML or Javascript. Does it get better? Yes it does, but you will need to see for yourself by trying IntraWeb.

Code Examination

Faster Web Development If you are a Delphi shop, there is no doubt your programmers can be up and running with IntraWeb in a matter of minutes while continuing to use their existing skills. You can develop web applications in days instead of months, and you can take on web projects previously deemed impossible or too time consuming. Now, can you honestly say that about any other web development tool? Conclusion This tutorial took the next step and demonstrated the ease of handling user input and managing multiple forms.However IntraWeb is far more powerful and has many more features than what has been demonstrated here. To see the full power of IntraWeb you need to look at the included demos and better yet, write your own application. The evaluation version is fully functional, so what are you waiting for? Download IntraWeb Now! Enviando texto HTML para uma janela do navegador: procedure TIWForm1.IWButton1Click(Sender: TObject); var sURL, sOpt, sNome: string; begin sURL := ''; sNome := 'Teste'; sOpt := 'scrollbars=no,width=300,height=100'; AddToInitProc('NovaJanela=window.open("'+sURL+'", "' + sNome + '","' + sOpt + '");'); AddToInitProc('NovaJanela.document.write("IntraWeb");'); AddToInitProc('NovaJanela.document.close();'); end; Lendo a URL que aparece na barra de endereo do navegador: WebApplication.Request.Referer

Tutorial de CSS:
http://www.w3schools.com/css/

Algumas propriedades do ServerController AppName: o nome da aplicao. AuthList: fora uma identificao ( aquele dialog do browser pedindo usurio e senha). Description: usada em vrios lugares, como no registro do servio, excees, etc. ExceptionDisplayMode: controla como as mensagens de exceo sero mostradas. HistoryEnabled: habilita o boto Voltar / Avanar, mas somente para efeitos de visualizao. HTMLHeaders: pode ser usado para inserir cabealhos extras na seo <HEAD> dos arquivos HTML gerados (ex.: colocar um CSS padro). InvalidCommandURL: o IntraWeb ir buscar pginas na URL quando uma ao invlida for passada. Port: A Porta que a aplicao ir escutar; RestrictlPs: s um ou alguns determinados IPs podero acessar (lembre-se dos proxies). SessionTimeout: tempo em que a sesso ser finalizada, se no houver atividades. ShowResyncWarning: aquela mensagem de aviso que aparece quando uma pgina que j no mais vlida. SupportedBrowsers: Navegadores suportados. TemplateDir: Diretrio dos Templates. TimeoutURL: o IntraWeb ir buscar pginas na URL quando a sesso tiver expirado. Retornando o Path da Aplicao... 1 . No uses, adicione SWSystem. 2. No evento onClick de um IWButton pro exemplo escreva: IWEdit.Text := gsAppPath;

Herana visual com IntraWeb e Delphi 7


http://bdn.borland.com/article/0,1410,30195,00.html

Using visual form inheritance with IntraWeb 5.1 in Delphi 7

Abstract: This article explains a way to be able to use visual form inheritance with IntraWeb (5.1). Something that normally is not working.

Introduction
When I started with my first real application in IntraWeb, I wanted to make a consistent layout through out my application. Since with IntraWeb you can make a web application just like a normal Delphi application: my first thought was: (visual) form inheritance (VFI). So I started happily programming making a baseform as a parent for all my other forms, putting on it a title bar, and started inheriting from it. And it worked: I had the title bar on all my forms! But after I started programming really functional forms, I soon also wanted to change something about my baseform, make the layout a bit nicer and better fitting with the forms I was making. And then it happened: I had added something to my baseform, compiled the application and it just gave an exception: "Control 'IWButton1' has no parent window". I hadn't changed anything really, except enhancing my baseform: and there wasn't even a IWButton1 on my baseform, it was on my mainform! Well after a little debugging, I looked at the IntraWeb newsgroups and it's website and soon found the answer: IntraWeb doesn't support visual form inheritance. You can use inherited code, but you can't inherit the visual layout...

Finding the problem...


Since I am a stubborn person (I wanted to use visual form inheritance!), and in my opinion problems are there to be solved, I started digging deeper in the problem. With the help of Delphi's VCL code (one of the things I love most about Delphi: you can always look at the source!) I soon found out in which part I had to search for the problem: the SetZOrderPosition method of TControl. When you add controls to a form you have inherited from (the baseform) the ordering of the controls on your descendant forms (in my case the Mainform) changes. You can see this ordering when you look at the dfm file of a descendant form: you see numbers in brackets [] after the controls. These numbers tell Delphi in which order the controls appear. In this SetZOrderPosition method there is a call to ValidParentForm (found in Forms.pas) that returns the parent form of the current control if that parent forms is a descendant of TCustomForm. And that was the problem: a TIWAppForm is not a descendant of TCustomForm!

...and trying to fix it.


Well only finding the problem doesn't solve it, I needed to find a way to fix it. My first thought was: I wanted that Borland had made ValidParentForm a virtual protected method of TControl, so anyone could override it, and the guys from IntraWeb could have made a special version that worked with IntraWeb forms. But since that wasn't the case, I had to go one level up to the SetZOrderPosition method. And found out that that one is private to TControl, so no chance of overriding that. (B.T.W. If that one could have be overridden it would have also meant that it had to be done in TIWBaseControl: and I would not be able to do that.) So I needed to go up one level: the caller of SetZOrderPosition which was in this case the SetChildOrder method of TWinControl, where this TWinControl was actually my Mainform. And the nice news was that SetChildOrder of TWinControl could be overridden! However if I did that there could be other problems because SetZOrderPosition was also called by other methods in TControl and TWinControl. But if that happened I would find out sooner or later.

Seeing that I needed to override SetChildOrder of my Mainform, and since that one inherited from my baseform: I put my implementation of SetChildOrder in my baseform. My implementation looked as follows:

So if the Child is a TIWBaseControl I call a special implementation of SetZOrderPosition else I just call the inherited version. That special implementation of SetZOrderPosition I put in a class called TIWBaseControlHelper:

To hack or not to hack?


Until so far it was simple. But now the real challenges appeared: I had to copy the implementation of SetZOrderPosition, but that implementation used a private field called FControls (see the VCL implementation of TControl.SetZOrderPosition in the Controls.pas unit). So I looked at what does the SetZOrderPosition has to do: it has to put itself at a certain position in it's parent list of controls. How can it do that, well look at the code I produced:

This code was of course inspired by the original TControl implementation: but the important part I had to rewrite. What it does is it first checks if it has a parent, then it searches for it's current position in the parent's control list and sees if it's new position is not the same. When it finds out it has to reposition, the hacking begins. We can't manipulate the parent's control list directly, but we can indirectly through the parent property of all the controls in the control list. So what I do is make a copy of the current control list and reposition our self in there. Then I set the parent of all the controls currently in the list to nil, so they are removed from the list and after that I add them again (in the correct order) to the list by setting their parent property back. So this results in a correctly ordered list. But this is not all that has to be done in this method! If it was we wouldn't have had any visual form inheritance problems, because this part already worked in the TControl implementation. The problem lied in the call to ValidParentForm in that implementation. First I thought I could just remove that call from my implementation, but I wasn't really sure and since the solution was not so hard, I made a call to a new function ValidParentIWForm. This function was simply based on the equivalent functions in Forms, I copied them and replaced references to TCustomForm to TIWBaseForm:

(I might be violating a little copyright of Borland here, but since this is actually the most obvious implementation and you can't use it if you don't have Delphi: I hope Borland allows me to publish it.) Now only one thing in my SetZOrderPosition code might need some explanation. I needed to call the PalletteChanged method of the ParentForm, but that is a protected method of TControl, so I used a standard hack to call a protected method: define a descendant class, and call the method by type casting to that descendant class:

Trying it out
And now the excitement begins: does it all work? So I started running my web application: and it gave no error! To really test it I made a lot of changes to my baseform, I made changes to my mainform and other forms: and it kept on working. I also changed the order of the controls on my baseform and mainform by selecting the control and right-click, choose Control -> sent to back and bring to front, since that actually manipulates that Z-Ordering, but it kept working.

Conclusion
So this finishes my solution for using visual form inheritance (VFI) with IntraWeb 5.1(.28) in Delphi 7 in application mode. We are using it for quite some time now, and haven't run into any bugs. You can get the source of this solution, including a small test project at codecentral. Included in that source is a TIWBaseVFIForm (in IWBaseVFIForm.pas) that you can use to inherited from. Of course you can also just copy the code from that form to your own base form. Remember one thing when using this solution: the developer of IntraWeb doesn't support VFI, so I have no idea if it will work for other versions of IntraWeb nor if it will work with pagemode! I also haven't tested this code with IntraWeb in Delphi 5 or 6, but a quick scan of the relevant source code of those implementations of TControl doesn't show any possible problems: so just try it out.

Using XMLBroker with IntraWeb - by Guinther Pauli


Abstract: This article will explain how to use the XMLBroker in a IntraWeb application, caching data and updates in browser. And finally, how to solve this updates to database server. Delphi 5 brought the Internet Express technology that allows the creation of Thin-Clients to MultiTier applications, based on a Web Browser. By using the XMLBroker we can connect it to a DataSetProvider and extract information from an application server in a XML format, which is sent to the browser. The data is then updated (creating a local cache called "delta") and sent back to the XMLBroker, which repasses the updating to the o DataSetProvider and finally to database server. The pages interface (the HTML code) is produced by the InetXPageProducer (former MidasPageProducer). The javaScript codes carry out the workability of the page, such as the manipulation of the XML data packet (this is basically done by xmldb.js and xmldisp.js files). The most interesting aspect of this architecture is that the user can work locally in the records, doing updates, inserts and deletes, without the need of a new requisition to the server in each operation. All the updates are sent to the server only when the user asks for the Apply command. The IntraWeb offers a similar option, available through the components of the IW Client Side palette. The problem is that the data sent to the browser are currently read-only. In this article we will create an IntraWeb application combining XMLBroker features. What we will basically do is to adapt the code generated by the InetXPageProducer to the IntraWeb.

To build this example you need IntraWeb 5.1 or higher and Delphi Enterprise. Some features used here are not available in the IntraWeb 5.0 and Delphi Professional. The Upgrade to IntraWeb 5.1 is free for Delphi 7 users.

The XMLBroker architecture with IntraWeb


The following picture shows the XMLBroker architecture, using IntraWeb as Web server application.

Creating the application and the database connection


Start a new IntraWeb Stand Alone application with a DataModule (File|New|Other|IntraWeb). Put a SQLConnection (from dbExpress) component in the DataModule and configure a connection to the Interbase EMPLOYEE.GDB database. After that, set its LoginPrompt property to False. Put a SQLDataSet (from dbExpress) and set its SQLConnection property. Type select CUST_NO, CUSTOMER, CONTACT_FIRST, CONTACT_LAST from CUSTOMER in its CommandText property. Put a DataSetProvider (from Data Access) component in the DataModule and set its DataSet property to SQLDataSet1. Put also a XMLBroker (from InternetExpress) and set its ProviderName property to DataSetProvider1, and Connected to True.

In this example we will not create an application server. So the DataSetProvider and XMLBroker will remain in the same DataModule. If you want to use a application server the steps are basically the same.

Creating the main form


Go to the main form and using IWLabels, IWEdits and IWButtons (from IW Standard) build your user interface, some like the picture below. Here we will use only the main table fields. Define the Name property of the IWEdits components to CUSTNO, CUSTOMER, CONTACTFIRST and CONTACTLAST respectively.

Here is the code that you must put in the ScriptEvents property (OnClick) of each one of the buttons: Button First (|<) Prior (<) Next (>) Last (>|) Insert Delete Undo Post Apply ScriptEvents (OnClick) If(xml_ready)FieldGroup1_Disp.first(); If(xml_ready)FieldGroup1_Disp.up(); If(xml_ready)FieldGroup1_Disp.down(); If(xml_ready)FieldGroup1_Disp.last(); If(xml_ready)FieldGroup1_Disp.newRow(); if(xml_ready)FieldGroup1_Disp.removeRow(); if(xml_ready)FieldGroup1_Disp.undo(); if(xml_ready)FieldGroup1_Disp.post(); document.SubmitForm.elements.IW_Action.value='IWBUTTON9'; if(xml_ready)XMLBroker1_RS.Apply(Submit_XMLBroker1, Submit_XMLBroker1.postdelta);

IWBUTTON9 in this case is the name of Apply Button Remember that JavaScript is case-sensitive!

Setting the WebMidas JavaScript files


Create a directory called files in the directory where you saved the project files (or where the stand alone application will be run). Copy to this directory the xmldb.js and xmldisp.js files that are in the directory $(DELPHI)/Source/WebMidas.

We need to do a little modification in the xmldb.js file so that there is not a conflict with the functions defined by the IntraWeb. Open this file and on line 313 change the declaration "Validate" for "DoValidate". Do the same on line 409. Attention: Note that even using IntraWeb you are making use of MIDAS/DataSnap technologies. The use of WebMidas technology requires a license from Delphi Enterprise. See the Borland documentation for further information about the developing with MIDAS/DataSnap. The next step is to create a JavaScript file which defines the global variables used by WebMidas. Create a file called defvars.js in the same directory (files). The content of the file is the following:
var var var var var var XMLBroker1_RS; DataForm1; FieldGroup1_Names; FieldGroup1_IDs; FieldGroup1_Disp; Submit_XMLBroker1;

Note that here the global variables are just defined. We initialize the variables in a second file that you must create in the same directory files, with the name initvars.js. Here is the content of the file:
XMLBroker1_RS = new xmlRowSet(XMLPACKET, null, null); DataForm1 = document.forms['SubmitForm']; FieldGroup1_Names = new Array("CUST_NO", "CUSTOMER", "CONTACT_FIRST","CONTACT_LAST"); FieldGroup1_IDs = new Array(DataForm1.CUSTNO, DataForm1.CUSTOMER, DataForm1.CONTACTFIRST, DataForm1.CONTACTLAST); FieldGroup1_Disp = new xmlDisplay(XMLBroker1_RS, FieldGroup1_IDs, FieldGroup1_Names, null); Submit_XMLBroker1 = document.forms['SubmitForm']; xml_ready=true;

Adding the JavaScript files


The next step is to include the WebMidas script files to document and the file that defines the global variables. We can do this using AddScriptFile method of TIWAppForm. In the OnCreate event of main form type this:
procedure TIWForm1.IWAppFormCreate(Sender: TObject); begin AddScriptFile('/files/xmldb.js'); AddScriptFile('/files/xmldisp.js');

AddScriptFile('/files/defvars.js'); end;

Note that we do not include the initialization file of the JavaScript (initvars.js) variables. This code must be added to the initialization of the HTML document, as we will do further on using AddToInitProc.

Initializing the XML packet the and WebMidas variables


Now we will add the the XML data packet to the document and include in the Initialize function the JavaScript code that initializes the WebMidas variables. In the OnRender event of the main form write the following:
procedure TIWForm1.IWAppFormRender(Sender: TObject); var SL : TStringList; V : OleVariant; I : integer; XML : TIWHTMLTag; //declare IWHTMLTag in uses begin XML:=TIWHTMLTag.CreateTag('XML'); try XML.AddStringParam('ID','XMLPACKET'); XML.Contents.AddText(DataModule1.XMLBroker1.GetXMLRecords(I ,V,[])); ExtraHeader.Clear; // clear ExtraHeaders ExtraHeader.Add(XML.Render); // add the XML Data Packet finally XML.Free; end; // add initialization variables to the Initialize function of IW document SL:=TStringList.create; try SL.LoadFromFile('files/initvars.js'); AddToInitProc(SL.Text); finally SL.Free; end; end;

Remember to declare IWHTMLTag in uses.

Getting the Delta and sending it to the AppServer


Open the HiddenFields property of the IntraWeb main form and add the following line:

postdelta= This is the field that will keep the Delta which will be sent back to the Web server application. The next step is to get the delta in the server and repass it to the XMLBroker. When we work with InternetExpress applications, the XMLBroker is automatically registered as the main component of dispatch. XMLBroker get the Delta and repassing it to the server application (DataSetProvider), without the need of requisition handle. We can also create a event handler for its OnGetResponse and apply the cache manually using the method ApplyXMLUpdates. Using XMLBroker with IntraWeb we can't to use this auto dispacth mechanism To manually get and apply the delta in the IntraWeb Application, in the OnClick event of IWButton9 type the following:
delta:=DataModule1.XMLBroker1.GetDelta(WebApplication.Request) ; // get delta DataModule1.XMLBroker1.ApplyXMLUpdates(delta,I); // apply delta

Declare a local string variable named delta, and an Integer named I. In the start of this article we place a Javascript code in the OnClick event of this button, to send the delta to the IntraWeb server. This function submit the form internally, without the IntraWeb handling. As we manually submit the form, then we have a problem, the OnClick event in the IntraWeb server never fire. To do this, we need to set manually a HiddenField named IW_Action (already defined by IW) to point to IWBUTTON9. We made this in the beginning of the article, in OnClick ScriptEvent of IWButton9, see:
document.SubmitForm.elements.IW_Action.value='IWBUTTON9';

Note that, in a normal IntraWeb application, this is made internally in the SubmitClick function. Then, when the form is submited, IntraWeb read this hidden field to map the right event in the server, in this case, OnClick of IWButton9.

Testing the application


Run the application. Include, update and delete some records, and note that there is no communication with the Web server. Click then on the button Apply to send the delta (XML) to the server that will repass the updated data to the XMLBroker. The following pictures shows an update in the two first records, and after the Apply we can see that the o Delta was applied correctly in the Interbase database.

Download
Download this example from CodeCentral Adicionando um hyperlink a um TIWImage

Para clicar em uma imagem, e ser redirecionado a um site, no evento onClick do seu componente TIWImage escreva WebApplication.GoToURL(www.intraw.hpg.com.br).

Para habilitar o Voltar/Avanar do navegador, ajuste a propriedade HistoryEnabled da unit IWServerController para true. Para rodar sua aplicao IntraWeb em uma porta especfica, ajuste a propriedade Port da unit IWServerController. Arquivos acessados com a URL so armazenados pelo browser. Se voce deseja criar arquivos dinmicos que no sejam armazenados, use ../filesnc/<filename>, em vez de, ../files/<filename>. Desta maneira o browser ser instrudo para no armazen-los. Quando voc desenvolve uma aplicao Intraweb para o Apache 2, voc precisa ter certeza que incluiu a unit IWInitApacheTwo na clusula uses. Se voc criou uma aplicao Apache 2 usando o wizard, isto feito automticamente. Obs: Voc precisa fazer as mudanas apropriadas na VCL do Delphi 7 antes de seus mdulos rodarem com o Apache 2. Mais detalhes no Dr. Bob's website em:
http://www.drbob42.com/Delphi7/Apache2040.htm

You might also like