IntraWeb Tutorial 2

84
Criando um dialog de confirmação 1. Adicione um TIWButton no form. 2. Implemente a propriedade Confirmation do TIWButton. 3. Desta forma, só irá chamar os eventos do botão, se no Dialog o usuário confirmar. Chamando um evento do botão com JavaScript 1. Adicione um TIWEdit e um TIWButton no form. 2. No evento OnClick do botão, digite: WebApplication.ShowMessage('teste'); 3. Na propriedade ScriptEvents do Edit, digite:

Transcript of IntraWeb Tutorial 2

Page 1: IntraWeb Tutorial 2

Criando um dialog de confirmação

1. Adicione um TIWButton no form.

2. Implemente a propriedade Confirmation do TIWButton.

3. Desta forma, só irá chamar os eventos do botão, se no Dialog o usuário confirmar.

Chamando um evento do botão com JavaScript

1. Adicione um TIWEdit e um TIWButton no form.

2. No evento OnClick do botão, digite:

WebApplication.ShowMessage('teste');

3. Na propriedade ScriptEvents do Edit, digite:

Page 2: IntraWeb Tutorial 2

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

Intraweb

Por Rafael E. Guarasemini

1.    O que é Intraweb?

Intraweb é uma biblioteca de componentes de desenvolvimento de htmls de forma simples, rápida 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 necessárias para o desenvolvimento de web pages, adicionando a facilidade de programação de ferramentas de desenvolvimento de sistemas.

O Intraweb esta disponível para várias linguagens de programação, entre elas:

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

Os componentes fornecem desenvolvimento de sites convencionais, dinâmicos, com acesso a base de dados, utilização de CSS, animações em geral.

Page 3: IntraWeb Tutorial 2

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 aplicações Intraweb, diferente do desenvolvimento tradicional de web site, gera apenas 1 arquivo, onde nele contém todo o projeto desenvolvido (com exceção base de dados e figuras).

3.1.           Tipos de sistemas em Intraweb

Para se desenvolver sistemas utilizando o Intraweb é necessário saber algumas coisas, principalmente, sobre onde ficará esta aplicação, isto quer dizer, qual será o sistema operacional e qual será o servidor de web disponível para se utilizar.

Tendo estas respostas é necessário 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 

Linux (utlizando o Borland Kylix)

Apache

Page 4: IntraWeb Tutorial 2

4.    Começando a utilizar o Intraweb

O Borland Delphi oferece as duas alternativas de desenvolvimento com o Intraweb citados no capítulo anterior. Sendo estes encontrados em:

No menu “File” “New” “Other”, na aba “Intraweb”, aqui você seleciona o tipo de aplicação que irá desenvolver. A figura abaixo demonstra a tela para se escolher o tipo de aplicação.

4.1.  Apache 2 DSO Application

     Desenvolvimento de aplicações para Windows utilizando  o servidor de web Apache versão 2 ou superior e se baseia no desenvolvimento de um objeto de compartilhamento dinâmico.

Este tipo de aplicação gera um arquivo com a extensão so (shared objetc)  que deve ser configurado para ser carregado no servidor Apache nas diretrizes de Load Modules no httpd.conf (arquivo de configurações do Apache), isso deve ser feito da seguinte maneira:

         o arquivo .so deve ser colocado no diretório de Modules do Apache;

         no arquivo de configurações do Apache, localize a chave Dynamic Shared Object, neste local é onde se configura os módulos que serão carregados com o Apache;

Page 5: IntraWeb Tutorial 2

         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 “variável de ponteiro do .so”

</Location>

Onde:

         nome do module gravado é o do projeto do Intraweb no Delphi, é encontrado no dpr (Projeto) da aplicação iniciada. Existe uma variável exportado do Delphi com o nome “apache_module name”. O conteúdo desta declaração é case sensitive.

         Nome do .so é nome do nome do arquivo gerado no final da compilação.

         /URL é o ponto de execução para um broswer, um exemplo seria /delphi. Esta variável é case sensitive

         variável de ponteiro do .so é uma variável case sensitive onde se inclui o nome da module com o sufixo –handle

Para se debugar uma aplicação deste tipo, deve-se fazer os seguinte passos:

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

Page 6: IntraWeb Tutorial 2

habilite no menu Tools Debugger Options a opção spawned processes

4.2.        Apache DSO Application

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 Formulário.

Este ícone apenas acrescenta uma nova página (Form) para se desenvolver.

4.4.        ISAPI Application

Utiliza para desenvolver aplicações para servidor Microsoft Windows utilizando servidores de Internet ISS.

Como compilação final, é gerado uma dll é deve ser configurada da seguinte forma (exemplo):

Copie do arquivo ISAPITER.dll do diretório de instalação do Delphi (bin\netscpXX) para C:\Netscape\Server\Nsapi\Examples (diretório de instalação do servidor)

No arquivo de configuração do servidor (OBJ.CONF), encontre a linha:

fn=load-types mimi-types=mimi.types

e inseria a seguir

Page 7: IntraWeb Tutorial 2

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 seção:

<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 página de html para se desenvolver na aplicação.

4.6.        Stand Alone Application

Cria uma aplicação para testes, tem funcionamento idêntico a qualquer outra aplicação com Intraweb, porém, 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

Page 8: IntraWeb Tutorial 2

4.7.        Stand Alone Application with Data Module

 Funcionamento idêntico ao Stand Alone Application, porém, já se inicia com um Data Module.

5.       O Intraweb no Delphi

O Delphi, a partir da versão 6, é dividido em duas blibliotecas de componetes, a VCL e a CLX

A VCL – Visual Components Library – são “todos” os componentes do Delphi, desde o TForm ao mais sinistro TTeeChart.

A CLX - Component Library for Cross-Platform – são quase todos os componentes do Delphi, são utilizados para se desenvolver uma aplicação 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 não são separedos em VCL e CLX, o que for VCL , também é CLX, isso pode ser reparado no código 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 criação de gráficos dinâmicos TIWDynamicChart (similar ao TDBChart da VCL).

Uma característica importante é que os componentes do Intraweb só podem ser utilizados em aplicações Intraweb e essas aplicações também só aceitam seus próprios componentes. Um jeito de se certificar disso é tentar colocar um componente da VCL/CLX em uma Intraweb Application.

Page 9: IntraWeb Tutorial 2

5.1. Os Componentes Standard

Nesta palheta estão 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 são 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 estão localizados os componentes para controle da base de dados para qual estiver se conectando.

Os componentes desta palheta são similares aos da palheta Data Controls da VCL/CLX, são componentes como DBGrid, DBLabel, DBEdit, DBNavigator e demais parecidos com a palheta da VCL/CLX.

Assim como os da VCL/CLX, eles são ligados com um Dataset. Os componentes dessa palheta podem ser vistos na figura abaixo:

5.3.        Os componentes Client Side

Nesta palheta estão componentes para “quem esta acessando a página html”. São componentes para gráficos e legendas dinâmicas, grids dinâmicos, com labels e navigators.

Os componentes dessa palheta podem ser vistos na figura abaixo:

5.4.        Os componentes Control

Page 10: IntraWeb Tutorial 2

Nesta palheta estão componentes para controle da página a ser exibida, contém controles para layout (templates) e produtores de páginas. Há um componente (IWLayoutMgrHTML) que contém 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 utilização dos componentes do Intraweb e modelos de aplicações que servem como base para maior desenvolvimento.

Não há um exemplo de como se fazer links entre as páginas do Intraweb, mas a estrutura é:

  TIwAppForm(RWebApplication.ActiveForm).Release;

 [nome do formulário que se quer abrir].Create(RwebApplication).Show;

6.1.        Exemplo 1

Neste primeiro exemplo, apenas mostraremos a cumplicidade da programação 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.

Page 11: IntraWeb Tutorial 2

A base para as mensagens é a mesma do Delphi, o conhecido showMessage, a diferença é que por se trabalhar em um servidor de Internet, não existe a IDE a plataforma de suporte Win32, devemos então 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 botão para executar a mensagem.

6.3.        Exemplo 3

Neste terceiro exemplo, iremos demonstrar a utilização de outros componentes que o Intraweb oferece.

Estes outros componentes são todos encontrados na VLC do Delphi e a sua manipulação é idêntica 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 estão referenciados a partir da VCL, para se utilizar os do Intraweb, basta colocar o prefixo IW ao nome dos componentes, com exceção do shape que no Intraweb se chama IWRectangle e é inferior ao shape.

Quanto a utilização, é idêntica a programação com a VCL.

Page 12: IntraWeb Tutorial 2

6.4.        Exemplo 4

Neste quarto exemplo, mostraremos como efetuar downloads a partir de uma aplicação Intraweb.

Estaremos utilizando a idéia de se mostrar o que pode ser feito donwload (utilizando uma rotina de SearRec em um diretório e mostrando tudo o que tiver extensão .JPG). O botão download faz o download da figura em stream e mostra no programa para qual estiver configurado para visualizar figuras.

Os componentes são os comuns do Intraweb e para se efetuar o download de algo, existe a seguinte função:

WebApplication.SendFile([arquivo],[string],[string],boolean)

6.5.        Exemplo 5

Neste quinto exemplo, iremos demonstrar como se efetuar upload a partir de uma aplicação Intraweb.

Page 13: IntraWeb Tutorial 2

Como podemos visualizar na figura abaixo, existe, visualmente, 3 componentes; porém, na verdade estamos utilizando apenas 2 componentes: um IWButton e um IWFile.

O IWFile é esse conjunto de caixa de texto e o botão 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 função do componente IWFile:

SaveToFile([path]) salva para o hd o arquivo escolhido

Ou

SaveToStream([path]) salva para uma stream (variável de memória)

6.6.        Exemplo 6

Neste sexto exemplo, iremos ver como acessar uma nova página ou site para uma nova janela.

Tudo se tratar apenas de uma chamada de função 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 botão para abrir.

6.7.        Exemplo 7

Neste sétimo exemplo, demonstraremos um refresh programado. Esse recurso é bastante usado em chats para se atualizar o página para novas mensagens.

Page 14: IntraWeb Tutorial 2

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 são 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 são os mais fáceis e comentados.

TIWTemplateProcessorHTML

Como ele, basta você colocá-lo no formulário Intraweb e setar a propriedade TemplateProcessor do seu formulário.

TIWLayoutMgrHTML

Funcionado idêntico ao TIWTemplateProcessorHTML, porém, ele tem incluído nele um editor de html (basta dar duplo clique sobre o componente), como visto na figura abaixo:

Page 15: IntraWeb Tutorial 2

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

Toda e qualquer página html (só pode ser html, ele não aceita htm), tem que ser salva em uma pasta chamada Templates que deve ser criada no mesmo nível que esta a sua aplicação;

Se você criar um html, colocá-lo na pasta Templates e no seu formulário Intraweb que vai utilizar este Template você colocar um botão e logo em seguida rodar a sua aplicação, acessar a página que você acabou de fazer....o que você terá ?

Você irá ver somente o seu html, nada dos componentes que você colocou que são do Intraweb.

Para que seja possível acessar os componentes do Intraweb, é necessário utilizar os tags dos componentes no html. Veja seqüência abaixo:

Page 16: IntraWeb Tutorial 2

Formulário no Delphi, há somente um IWText, um IWButton e um componente para utilização de Template

Este é a visualização do html com o sistema rodando, perceba que os componentes visuais do Intraweb (IWText e IWButton) não

aparecem

Page 17: IntraWeb Tutorial 2

Já nesta figura, colocamos no código 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 aplicação, os componentes do Intraweb estarão acessíveis.

6.9.   Exemplo 9

Neste nono exemplo, demonstraremos a utilização de gráficos estáticos e dinâmicos.

Page 18: IntraWeb Tutorial 2

A utilização de qualquer de um dos tipos de gráficos e bastante simples, é somente necessário saber utilizar o componente IWClientSideDatasetDBLink ou IWClientSideDataset onde se pode ligar com um DataSet (IWClientSideDatasetDBLink ) ou inserir os registro manualmente (IWClientSideDataset).

O componente responsável pela geração do gráfico é o IWDynamicChart e opcionalmente pode se utilizar legendas com o componente IWDynamicChartLegend.

Nesta figura, estamos demonstrando um gráfico estático, onde somente setamos no componente do gráfico qual será a coluna e a

linha

Page 19: IntraWeb Tutorial 2

Nesta figura, o gráfico é gerado dinamicamente, existe 2 combobox onde se seleciona qual será os campos na vertical e horizontal

6.10.  Exemplo 10

Neste décimo exemplo, demonstraremos como se gerar grades (grids) estaticamente e dinamicamente.

A utilização dos grid estático é feita a partir de um DataSet ligado ao componente IWDBGrid que tem a sua utilização idêntica ao DBGrid da VLC.

A utilização de grid dinâmico é feita a partir de um DataSet ligado ao componente IWDynGrid, onde já será gerado um grid com filtros e ordem automaticamente.

Page 20: IntraWeb Tutorial 2

Aqui é demonstrado um grid estático com os registro de uma tabela, no caso, um arquivo xml

Aqui é demonstrado um grid dinâmico onde existe filtros e ordem dinamicamente montados

6.11. Exemplo 11

Neste décimo primeiro exemplo, mostraremos como utilizar menus no Intraweb.

Assim como em uma aplicação normal com o MainMenu da VLC, você somente necessita colocar um IWMenu e liga-lo com o formulário do Intraweb, porém, há uma necessidade de se colocar também um TMainMenu da VCL, pois o componente do Intraweb utiliza como base ele.

Para isso, basta colocar um TMainMenu no formulário Intraweb, montar a estrutura de menus. liga-lo  com o IWMenu e pronto. A estrutura de menus feita no TMainMenu estará disponível no IWMenu.

O funcionamento pode ser visto na figura abaixo:

Page 21: IntraWeb Tutorial 2

6.12.  Exemplo 12

Neste décimo segundo exemplo, demonstraremos como se fazer um formulário de inserção 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 é idêntica de quando se faz um formulário de inserção para aplicações normais, e a maneira de se fazer a inserção 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 é necessário se fazer em aplicações comuns, são feitas da mesma maneira.

7.           Conclusões finais

Como visto em todo este documento, a utilização do Intraweb é algo bastante simples, principalmente pelo motivo de se programar da mesma maneira que se programa em aplicações normais, ganhando em rapidez e eficiência, pois

Page 22: IntraWeb Tutorial 2

estará aproveitando tudo o que a ferramenta Borland Delphi oferece para programação.

8.           Bibliografia

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

Clique aqui e faça download dos exemplos utilizados nesse artigo.

 

Sobre o Autor

Rafael E. Guarasemini - Último ano de Bacharel de Sistemas de Informação pela Faculdade Claretianas de Rio Claro. Programador Delphi a 5 anos e membro do NUPEDS (Núcleo de Pesquisa e Desenvolvimento de Sistemas da Faculdade Claretianas

COMENTÁRIOSCésar Nascimento - 30/05/2003 - 13:42:11

Cara, peguei um sistema de instalação desenvolvido por você que nunca tinha vista antes tão eficiente e amigável. 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 máquinas diferentes envio determinada consulta diferente de cada maquina e ao dar enter ao mesmo tempo, retorna a mesma consulta nas duas máquinas mesmo sendo consulta diferente.como posso solucionar esse problema?

agradeço se puder me ajudar ................................................

Rafael E. Guarasemin - 05/06/2003 - 12:15:01 LM,mande uma email para mim, assim fica mais facil de [email protected]

[]´s ................................................

Marcos P. Gomes - 09/06/2003 - 16:57:53 Vamos centralizar as dúvidas na [email protected] esse espaço é apenas para comentários gerais sobre o material acima.

Page 23: IntraWeb Tutorial 2

Atenciosamente

Marcos P. GomesModerador

................................................ 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, não dá para vc publica-lo diretamente, vc pode baixar um programa na community do Guinther que transforma aplicações 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 relação entre o form da página 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 aplicações stand alone para dll, qual o endereço 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,

Page 24: IntraWeb Tutorial 2

Primeiramente quero parabenizá-lo pelo artigo de intraweb escrito no delphibr.Bem gostaria de uma orientação, como faço para migrar um sistema inteiro feito em delphi 5 para web usando delphi 7 se possível, me falaram sobre usas xml, mas tenho nem noção por onde começar por isso, gostaria de saber como devo começar o pelo menos onde poderia procurar algo a respeito.

Desde já agradeço................................................

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 Guerço Rodri - 27/07/2003 - 11:53:17 DEPOIMENTO

Aqui em nossa empres, nosso grupo de trabalho já avançou bastante em IntraWeb. Já contamos com três aplicativos usando esta tecnologia, inclusive, uma delas atende a negócio pela internet onde nosso cliente tendo com clientes três bancos.É sem dúvida uma alternativa excelente.Estamos a disposição para suporte, já que contamos também com um curso de treinamento especializado.

[email protected] ................................................

Norival Hübner - 28/07/2003 - 09:16:17 Parabens pelo artigo. Está de excelente qualidade.

Apoveitando a oportunidade, gostaria de saber se as Aplicações Intraweb desenvolvidas com do Delphi 7 Enterprise precisam ser licenciadas.

desde já obrigado.

Norival Hübner

[email protected]................................................

Page 25: IntraWeb Tutorial 2

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 Parabéns pro este artigo! tenho algumas aplicações em delphi e gostaria de utilizar esta ferramenta. Gostaria de obter mais informações a respeito o uso do intraweb com delphi 7.Obrigada.

................................................ Envie seu comentário

Nome

Comentários

Delphi 7 - WEB Services com IntraWEB

Por Danilo Bertholini

Duas tecnologias que chamaram atenção no Delphi 7 foram os web services e o novo framework para desenvolvimento RAD para WEB o IntraWEB, nesta matéria verermos como utilizar estas duas tecnologias em conjunto para criar um cliente web service. Como exemplo utilizaremos o famoso serviço de tradução BabelFish, para você que não viu as duas matérias 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 aplicação IntraWEB do tipo Stand Alone Application adicione ao formulário principal (FormMain) os seguintes componentes:

Page 26: IntraWeb Tutorial 2

IWEdit, IWButton, IWLabel - Todos localizados na guia IWStandard.

HTTPRIO - Localizado na guia WEB Services.

Posicione-os de acordo com a figura1.

Figura 1 - o Formulário principal.

Agora com o design de nosso exemplo pronto, vamos importar o serviço WEB para isso vá em File | New | Other na guia WEB Services selecione a opção WSDL Importer, na próxima janela digite no campo o endereço do WSDL: http://www.xmethods.net/sd/2001/BabelFishService.wsdl feito isso é só seguir na importação do serviço, veja no primeiro artigo da série "crie seu tradutor" passo-a-passo como importar um serviço. Com nosso serviço 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 configuração do Server Controller.

Volte ao formulário principal "FormMain" e selecione o componente HTTPRIO1 e o configure de acordo com o quadro abaixo:

WSDLLocation - http://www.xmethods.net/sd/2001/BabelFishService.wsdlService - BabelFishPortPort - BabelFishPort

Page 27: IntraWeb Tutorial 2

Pronto, Nosso HTTPRIO foi configurado! Agora pressione ALT+F11 para utilizar a Unit do serviço importado e no evento onclick do IWButton digite as seguintes linhas de códigos:

var// Declara uma referência à interface do serviço,// criada pelo wizard na importação.ws : BabelFishPortType;begin// Inicializa o serviço.ws := HTTPRIO1 as BabelFishPortType;// Invoca o serviço e passa ao IWlabel os resultado.IWLabel1.Caption := ws.BabelFish('pt_en',IWedit1.Text);end;

Agora é só executar nossa aplicação! 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 execução.

Figura 3 - O Servidor Stand Alone

Figura 4 - A aplicação em execução.

Page 28: IntraWeb Tutorial 2

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 File Size Last Updated

IntraWeb OpenSource Pack IW 5 & 6 - ArcIWOpenSource6.zip 55597 5/24/2003

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

IntraWeb OpenSource Pack - ArcIWOpenSource.zip 91955 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

Page 29: IntraWeb Tutorial 2

Installing Apache Controlling Apache Writing A Shared Module Using The Shared Module Debugging Shared Modules About Brian Long

IntroductionBack 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.

Page 30: IntraWeb Tutorial 2

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 2Apache 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:

Page 31: IntraWeb Tutorial 2

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 ApacheBefore 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:

Page 32: IntraWeb Tutorial 2

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:

Page 33: IntraWeb Tutorial 2

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 ApacheWhen 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.

Page 34: IntraWeb Tutorial 2

Figure 4: The Apache service Start Menu Group

If you chose the other option (manually starting Apache in Figure 3), the Control Apache Server menu will not be present, but you will have one extra menu item under Apache httpd Server, which says Start Apache in Console.

If you installed Apache as a service, it will be running each time you start Windows. You can stop Apache with the Stop menu item and start it with the Start item. The Restart item will 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 Start Apache in Console item will start the Apache process in a console window (in Apache 1.3.4 and earlier, this option was called Apache Server). This process can 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:

Page 35: IntraWeb Tutorial 2

Figure 5: The default Apache homepage

Writing a Shared ModuleTo create a shared module in Delphi 6, choose File | New | Other..., then choose Web Server Application. In the Web Server Application wizard, choose Apache Shared Module (DLL) and press OK. This creates a DLL-based WebBroker application, where we need to focus on the project file (choose Project | View Source).

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,

Page 36: IntraWeb Tutorial 2

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 Project1_module, resulting 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

Page 37: IntraWeb Tutorial 2

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 ModuleThe 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 (Ctrl+F9) and the shared 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 /delphi to be handled by your shared module.

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:

module_record_name is the symbol exported by the project file and is case-sensitive. In Listing 2 you can see this is ApacheTest_module

library_name is taken from the ModuleName 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_ApacheTest.so

URL is the case-sensitive URL portion that identifies what URLs should be serviced by the shared module. For the example, this will be /delphi

content_type is taken from the case-insensitive ContentType variable and defaults to a lowercase string that includes the module name without the

Page 38: IntraWeb Tutorial 2

extension, with -handler appended. In my example, this is mod_apachetest-handler

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 Location directives to the configuration file and then save it.

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 Location directive is case-sensitive, browsing to http://localhost/Delphi will give an error 404, page not found error.

Debugging Shared ModulesIn 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... dialog, enter the full path to Apache in the Host Application field:

Page 39: IntraWeb Tutorial 2

Figure 7: Telling Delphi how to debug your shared module

Now go to the debugger options dialog (Tools | Debugger Options...) and enable the Debug spawned processes checkbox.

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 F9), Delphi launches Apache, which then loads up the shared module allowing it to be 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 (Ctrl+F2) as Apache may not shut down properly. Either use the Start menu item (if available) or the corresponding command-line or, if Apache is running in a console window, press Ctrl+C in that window.

About Brian LongBrian 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.

Page 40: IntraWeb Tutorial 2

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:    Download

For Delphi 5 and other:    Download 

 

Intraweb v.3.5.0

For Delphi 6:    Download

For Delphi 5 and other:    Download  

     

Run Live demo !   

Page 41: IntraWeb Tutorial 2

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:

Page 42: IntraWeb Tutorial 2

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

Page 43: IntraWeb Tutorial 2

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:

Page 44: IntraWeb Tutorial 2

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

Page 45: IntraWeb Tutorial 2

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

Page 46: IntraWeb Tutorial 2

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:

Page 47: IntraWeb Tutorial 2

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

Page 48: IntraWeb Tutorial 2

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

Page 49: IntraWeb Tutorial 2

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

Page 50: IntraWeb Tutorial 2

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:

procedure TIWForm1.IWButton1Click(Sender: TObject);  begin   end;  

Add the following code to the event:

procedure TIWForm1.IWButton1Click(Sender: TObject);  var    s : string;  begin    s := editName.Text;    if Length(s) = 0 then    begin       WebApplication.ShowMessage('Please tell me your name!');    end    else    begin       WebApplication.ShowMessage('Hello ' + s + '!');       editName.Text := '';    end;  end;  

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

Page 51: IntraWeb Tutorial 2

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 !

Page 52: IntraWeb Tutorial 2

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.

// To handle the button click all we did was define an OnClick! End of story! WOW!   procedure TIWForm1.IWButton1Click(Sender: TObject);  var    s : string;  begin     // Read the users entered text from the Text property.     // No parsing of HTTP variables, no adaptors, no bindings.     // JUST like Delphi! Wow again!     s := editName.Text;     // See if the user entered anything, or if they left it blank!     if Length(s) = 0 then    begin       // Show a message dialog. Could it be any simpler?        WebApplication.ShowMessage('Please tell me your name!');    end    else    begin       // Show a message dialog. Could it be any simpler?        WebApplication.ShowMessage('Hello ' + s + '!');   

Page 53: IntraWeb Tutorial 2

    // Clear the edit box. The properties are not only for reading, but writing too!        editName.Text := '';    end;  end;     

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:

Page 54: IntraWeb Tutorial 2

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:

Page 55: IntraWeb Tutorial 2

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:  

Page 56: IntraWeb Tutorial 2

procedure TformHello.IWLink1Click(Sender: TObject);  begin    Release;  end;   

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:

uses    ServerController, IWBaseForm, unit2; //Note - if you changed your second form's filename - change this!     procedure TIWForm1.IWButton1Click(Sender: TObject);  var    s : string;  begin    s := editName.Text;    if Length(s) = 0 then    begin       WebApplication.ShowMessage('Please tell me your name!');    end    else    begin       with TformHello.Create(WebApplication) do       begin          Title := 'Saying Hello to ' + s + '!';          lablHello.Caption := 'Hello ' + s + '!';          Show;          editName.Text := '';       end;    end;  

Page 57: IntraWeb Tutorial 2

end;  

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

procedure TIWForm1.IWButton2Click(Sender: TObject);  begin    WebApplication.Terminate('Goodbye!');  end;   

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:

Page 58: IntraWeb Tutorial 2

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

Page 59: IntraWeb Tutorial 2

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

procedure TformHello.IWLink1Click(Sender: TObject);  begin     // This frees the current form and returns to the previous active form        Release;  end;   procedure TIWForm1.IWButton1Click(Sender: TObject);  var    s : string;  begin    s := editName.Text;    if Length(s) = 0 then    begin       WebApplication.ShowMessage('Please tell me your name!');  

Page 60: IntraWeb Tutorial 2

  end    else    begin        // Create a new form. It is owned by WebApplication which is       // IntraWeb's equivalant of Application. WebApplication       // represents the user's session.        with TformHello.Create(WebApplication) do       begin           // Set the page title           Title := 'Saying Hello to ' + s + '!';           // Set the caption of our label on the second form           lablHello.Caption := 'Hello ' + s + '!';           // Show the form           Show;          editName.Text := '';       end;    end;  end;   procedure TIWForm1.IWButton2Click(Sender: TObject);  begin     // Terminate the user's application and display a message.    // There are many variants of Terminate that can terminate    // with messges, redirets, etc...     WebApplication.Terminate('Goodbye!');  end;     

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?

Page 61: IntraWeb Tutorial 2

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 endereço do navegador:

WebApplication.Request.Referer

Tutorial de CSS:

http://www.w3schools.com/css/

Algumas propriedades do ServerController

• AppName: é o nome da aplicação.

• AuthList: força uma identificação ( aquele dialog do browser pedindo usuário e senha).

• Description: usada em vários lugares, como no registro do serviço, exceções, etc.

• ExceptionDisplayMode: controla como as mensagens de exceção serão mostradas.

• HistoryEnabled: habilita o botão Voltar / Avançar, mas somente para efeitos de visualização.

• HTMLHeaders: pode ser usado para inserir cabeçalhos extras na seção <HEAD> dos arquivos HTML gerados (ex.: colocar um CSS padrão). • InvalidCommandURL: o IntraWeb irá buscar páginas na URL quando uma ação inválida for passada.

• Port: A Porta que a aplicação irá escutar;

• RestrictlPs: só um ou alguns determinados IPs poderão acessar (lembre-se dos proxies).

Page 62: IntraWeb Tutorial 2

• SessionTimeout: tempo em que a sessão será finalizada, se não houver atividades.

• ShowResyncWarning: aquela mensagem de aviso que aparece quando uma página que já não é mais válida. • SupportedBrowsers: Navegadores suportados.

• TemplateDir: Diretório dos Templates.

• TimeoutURL: o IntraWeb irá buscar páginas na URL quando a sessão tiver expirado.

Retornando o Path da Aplicação...1 . No uses, adicione SWSystem.

2. No evento onClick de um IWButton pro exemplo escreva:

IWEdit.Text := gsAppPath;

Herança 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

Page 63: IntraWeb Tutorial 2

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:

procedure TIWBaseVFIForm.SetChildOrder(Child: TComponent; Order: Integer);begin if Child is TIWBaseControl then TIWBaseControlHelper(Child).SetZOrderPosition(Order) else inherited;end;

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:

type TIWBaseControlHelper = class(TIWBaseControl) public procedure SetZOrderPosition(Position: Integer); end;

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

Page 64: IntraWeb Tutorial 2

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:

procedure TIWBaseControlHelper.SetZOrderPosition(Position: Integer);var I, J, Count: Integer; ParentForm: TIWBaseForm; TmpParent: TWinControl; TmpControls: TList;begin if Parent = nil then Exit;

// First find our current position (in I) Count := Parent.ControlCount; I := 0; while I < Count do begin if Parent.Controls[I] = Self then Break; Inc(I); end;

if I = Count then Exit; // strange we are not in our parent list?

if Position < 0 then Position := 0; if Position >= Count then Position := Count - 1; if Position <> I then begin // re-position, but since we can't directly manipulate Parent.Controls, // we need to hack and make a copy in TmpControls TmpControls := TList.Create; try for J := 0 to Count-1 do TmpControls.Add(Parent.Controls[J]); // delete ourselves from the list: TmpControls.Delete(I); // and insert at new position TmpControls.Insert(Position, Self); // save Parent (we'll be setting it to nil in the next lines) TmpParent := Parent; // remove all controls from the Parent's Controls list // we do that by setting the Parent property of the controls to nil while TmpParent.ControlCount > 0 do TmpParent.Controls[0].Parent := nil; // And put them back in in our TmpControls order for J := 0 to Count-1 do TControl(TmpControls[J]).Parent := TmpParent; finally TmpControls.Free; end;

Page 65: IntraWeb Tutorial 2

// Invalidate; Not necessary in IntraWeb. ParentForm := ValidParentIWForm(Self); if csPalette in ParentForm.ControlState then THackIWBaseForm(ParentForm).PaletteChanged(True); end;end;

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:

// next funcs base on Forms.GetParentForm and Forms.ValidParentFormfunction GetParentIWForm(Control: TControl): TIWBaseForm;begin while Control.Parent <> nil do Control := Control.Parent; if Control is TIWBaseForm then Result := TIWBaseForm(Control) else Result := nil;end;

function ValidParentIWForm(Control: TControl): TIWBaseForm;begin Result := GetParentIWForm(Control); if Result = nil then raise EInvalidOperation.CreateFmt(SParentRequired, [Control.Name]);end;

(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:

Page 66: IntraWeb Tutorial 2

type THackIWBaseForm = class(TIWBaseForm);

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 page’s 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.

Page 67: IntraWeb Tutorial 2

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 IntraWebThe following picture shows the XMLBroker architecture, using IntraWeb as Web server application.

Creating the application and the database connectionStart 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.

Page 68: IntraWeb Tutorial 2

Creating the main formGo 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 ScriptEvents (OnClick)First (|<) If(xml_ready)FieldGroup1_Disp.first();Prior (<) If(xml_ready)FieldGroup1_Disp.up();Next (>) If(xml_ready)FieldGroup1_Disp.down();Last (>|) If(xml_ready)FieldGroup1_Disp.last();Insert If(xml_ready)FieldGroup1_Disp.newRow();Delete if(xml_ready)FieldGroup1_Disp.removeRow();Undo if(xml_ready)FieldGroup1_Disp.undo();Post if(xml_ready)FieldGroup1_Disp.post();

Applydocument.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 filesCreate 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.

Page 69: IntraWeb Tutorial 2

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 XMLBroker1_RS;var DataForm1;var FieldGroup1_Names;var FieldGroup1_IDs;var FieldGroup1_Disp;var 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 filesThe 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;

Page 70: IntraWeb Tutorial 2

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 variablesNow 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 usesbegin 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.

Page 71: IntraWeb Tutorial 2

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 deltaDataModule1.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 applicationRun 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.

Page 72: IntraWeb Tutorial 2

DownloadDownload 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’).

Page 73: IntraWeb Tutorial 2

Para habilitar o Voltar/Avançar do navegador, ajuste a propriedade HistoryEnabled da unit IWServerController para true.

Para rodar sua aplicação IntraWeb em uma porta específica, ajuste a propriedade Port da unit IWServerController.

Arquivos acessados com a URL são armazenados pelo browser. Se voce deseja criar arquivos dinâmicos que não sejam armazenados, use ../filesnc/<filename>, em vez de, ../files/<filename>. Desta maneira o browser será instruído para não armazená-los.

Quando você desenvolve uma aplicação Intraweb para o Apache 2, você precisa ter certeza que incluiu a unit IWInitApacheTwo na cláusula uses. Se você criou uma aplicação Apache 2 usando o wizard, isto é feito automáticamente.Obs: Você precisa fazer as mudanças apropriadas na VCL do Delphi 7 antes de seus módulos rodarem com o Apache 2. Mais detalhes no Dr. Bob's website em:http://www.drbob42.com/Delphi7/Apache2040.htm