Sábado, 16 de Junho de 2007
Delphi with indy - part 1 / Delphi com indy - parte 1
Indy with Delphi (part 1)
Connecting Delphi with an Web Service (1)
Hello!
In this article we’ll connect a Delphi application with a web service provided by www.random.org. This service generates a gave amount of random integer numbers in a given range (max and min values). For made the connection it’s highly recommended to use DELPHI 7 or higher and the INDY COMPONENTS FOR DELPHI, that can be downloaded here: (put link here). The Delphi already has a version of INDY (version 7), but I’ll use the version 10.
Testing the service in the Browser
Before we open our Delphi, we’ll make a small test via browser. The syntax of the service is:
http://www.random.org/integers/?num=X&min=Y&max=Z&col=1&format=plain&rnd=new&base=W
Where:
X: is the amount of numbers that will be generated. If x=6 the service will return 6 random numbers.
Y: is the minimum value of the numbers that will be generated. IMPORTANT: Y MUST BE GREATER THAN –1000000000 AND LOWER THAN 1000000000
Z: is the maximum value of the numbers, it MUST BE: GREATER THAN –1000000000, GREATER THAN Y, LOWER THAN 1000000000.
W: is the base of the numbers. It can be 2(binary), 8(octal), 10(decimal) or 16(hexadecimal).
Col=1: is the number of columns that the numbers will be divided between. If the column number was lower than X, the system will return an error. I use 1 just for example.
Format=plain: It can be “plain” or “HTML”, if it is “html” the returned page will contain more items them just numbers, and it will be difficult for de delphi locate our numbers, so “plain” is the better way.
Let’s start our tests generating 6 decimal random numbers between 1..20
So the address is:
http://www.random.org/integers/?num=6&min=1&max=20&col=1&format=plain&rnd=new&base=10
“Delphing”
Now you know how the service works, I suggest that you test with different maximum and minimum values, in different ranges and bases.
To call the service we’ll use INDY and for show the results, memo. Create a new application and add the following components:
3 TspinEdit -> tab “Samples”
1 TcomboBox -> tab “Standard”
1 Tmemo -> tab “Standard”
1 TIdHTTP -> tab “Indy Clients”
1 Tbutton -> tab “Standards”
We’ll set the following properties:
SpinEdit1:
Name: Min
MaxValue: 1000000000
MinValue: -1000000000
Value: 1
SpinEdit2:
Name: Max
MaxValue: 1000000000
MinValue: -1000000000
Value: 6
SpinEdit3:
Name: Amt
Value: 6
ComboBox1:
Name: Base
Add the following (line-separated) items:
2
8
10
16
Style: csDropDownList
Explaining the properties
The max and min values are the range that the values in the spin edit must be in. Value is the initial value (if the user don’t set anyone, the system will use this).
In the comboBox the items are the possible bases for the system (binary, octal, decimal and hexadecimal), the property “style” was set as “csDropDownList” because this turn the items unchangeable by the user.
TIP: Add labels with the texts “max” “min” e “amnt” above the respective spin edit
The process is simple, we have to make a request using the same syntax that we used in the browser and make our system read the results. In the “public” part of the code, that is located in the topper part of the code, put the following code:
v_max, v_min, v_amt: integer;
v_base: string;
The first three variables will hold the numerical parameters of the address; the variable “v_base” holds the base (obvious ;D )
In the button’s 1 OnClick event erase the “begin” and the “end;” commands and put this (explaining commented out):
var
resp: TStringStream; //this variable will hold the answer of the server
adr: string; // the address that will be called, like in the browser
begin
v_amt := amt.Value; //holds the amount of numbers, set in the spin edit
v_base := base.Text; //holds the base
v_min := min.value; //minimum value
v_max := max.Value; //maximum value
adr := 'http://www.random.org/integers/?num='+IntToStr(v_amt)+'&min='+IntToStr(v_min)+'&max='+IntToStr(v_max)+'&col=1&format=plain&rnd=new&base='+v_base; //set the address, “IntToStr” converts an integer in a string
resp := TStringStream.Create(''); //initialize the stream with an empty string
idHttp1.Get(adr,resp); // make the request in the “adr” address and writes the answer in “resp”
memo1.Lines.LoadFromStream(resp); //loads the server’s answer in the memo
resp.Free;
end;
Testing
To test this you have to (of course) be connected to the Internet. Just set the spins and the comboBox and wait a bit for the results. It’s really useful this service, if you want to make an on-line game and use dice, you can use the service for generate 1 random number from 1 to 6. This can be used didactically for teach connecting (as I made here). I hope you liked!
Please contact:
orkut: “81duz1d0”
Usando Indy no Delphi (parte 1)
Conectando o delphi com um serviço on-line
Olá!
Nesse artigo nós vamos conectar o delphi com um serviço na internet oferecido por www.random.org. Esse serviço gera uma quantidade fornecida de números dentro de um intervalo numérico. Para realizar a conexão eu recomendo o uso do Delphi 7 ou superior e os componentes INDY, que podem ser baixados de: (http://downloads.atozed.com/indy/indy10.1.5_d7.exe). O Delphi já tem uma versão do INDY (versão 7) mas eu vou usar a 10.
Testando o serviço no browser
Antes de abrirmos o delphi, vamos fazer um pequeno teste através do browser. A sintaxe do serviço é:
http://www.random.org/integers/?num=X&min=Y&max=Z&col=1&format=plain&rnd=new&base=W
Onde:
X: é a quantidade de números que serão gerados. Se x=6 o serviço vai gerar 6 números aleatórios.
Y: é o valor mínimo dos números. IMPORTANTE: Y tem que ser maio do que –1000000000 e menor que 1000000000
Z: é o valor máximo dos números. IMPORTANTE: Z TEM QUE SER MAIOR DO QUE –1000000000, MAIOR DO QUE Y E MENOR QUE 1000000000.
W: é a base dos números. Pode ser 2(binário), 8(octal), 10(decimal) ou 16(hexadecimal).
Col=1: é o número de colunas que os números serão divididos. Se o número de colunas for menor que X o sistema retornará um erro.
Format=plain: Isso pode ser “plain” ou “HTML”, se for “HTML” o sistema vai retornar uma página que contém mais elementos do que apenas os números e Será difícil para o delphi localizá-los
Vamos começar os testes gerando 6 números decimais entre 1 e 20
Então o endereço é:
http://www.random.org/integers/?num=6&min=1&max=20&col=1&format=plain&rnd=new&base=10
“Delphizando”
Agora você já sabe como o serviço funciona, eu sugiro que você teste com valores máximos e mínimos diferentes em diferentes quantidades e bases.
Para chamar o serviço nós usaremos o INDY e para exibir os resultados um memo. Crie uma nova aplicação e adicione os seguintes componentes:
3 TspinEdit -> aba “Samples”
1 TcomboBox -> aba “Standard”
1 Tmemo -> aba “Standard”
1 TIdHTTP -> aba “Indy Clients”
1 Tbutton -> aba “Standards”
Modifique as seguintes propriedades:
SpinEdit1:
Name: Min
MaxValue: 1000000000
MinValue: -1000000000
Value: 1
SpinEdit2:
Name: Max
MaxValue: 1000000000
MinValue: -1000000000
Value: 6
SpinEdit3:
Name: Amt
Value: 6
ComboBox1:
Name: Base
Adicione os seguintes itens separados linha-a-linha:
8
10
16
Style: csDropDownList
Explicando as propriedades
Os valores MaxValue e MinValue formam o intervalo que o valor dos Spin edit têm que estar. Value é o valor inicial (se o usuário não inserir nenhum, o sistema utilizará esse).
Na comboBox, os itens são as possíveis bases no sistema (binário, octal, decimal e hexadecimal), a propriedade style foi posta como csDropDownList porque isso faz com que os usuários não consigam modificar os itens.
Dica: para facilitar a localização, coloque labels com os textos “min” “max” e “qtd” sobre os spins desse valores.
Chamando os números
O processo é simples, nós temos que solicitar os números utilizando a mesma syntax do browser e fazer o sistema ler os resultados. Na parte public do código, que está no alto do código-fonte, coloque o seguinte:
v_max, v_min, v_amt: integer;
v_base: string;
As primeiras 3 variáveis conterão os parâmetros numéricos do endereço; a variável v_base conterá a base (óbvio ;D )
No evento onClick do botão um apague os comandos begin e end; e coloque isso (explicação nos comentários):
var
resp: TStringStream; //essa variável conterá a resposta do servidor
adr: string; //o endereço que será acessado, igual no browser
begin
v_amt := amt.Value; //contém a quantidade de números
v_base := base.Text; //contém a base
v_min := min.value; //valor mínimo
v_max := max.Value; //valor máximo
adr := 'http://www.random.org/integers/?num='+IntToStr(v_amt)+'&min='+IntToStr(v_min)+'&max='+IntToStr(v_max)+'&col=1&format=plain&rnd=new&base='+v_base; //o endereço, IntToStr converte um número em string
resp := TStringStream.Create(''); //inicializa a stream com uma string vazia
idHttp1.Get(adr,resp); //faz a chamada em “adr” e põe a resposta em “resp”
memo1.Lines.LoadFromStream(resp); //coloca a resposta no memo
resp.Free;
end;
Testando
Para testar você tem que estar conectado na internet. Apenas digite algum valor no comboBox e nos spins então espere um pouco pelos resultados.
Espero que tenha gostado
No próximo artigo: aprofundando em conexões, indy com autenticação não-SSL (ssl no terceiro artigo ;D )
Por favor contate:
bidu.pub@gmail.com
orkut: “81duz1d0"
Domingo, 3 de Junho de 2007
Regex with Delphi/Regex no delphi - Index (índice)
Here is the links for the posts about regex (english)
Regex with delphi 1
Regex with delphi 2 (databases)
--------------------------------------------------------------
Olá!
Aqui está os links para os posts sobre regex (portugês)
Regex no delphi 1
Regex no Delphi 2 (banco de dados)
Sexta-feira, 1 de Junho de 2007
Regex no Delphi (1)
Um problema comum para nós, programadores, é o chamado CharCase, ou simplesmente “caixa”. Por exemplo: UM TEXTO ESCRITO DESTA MANEIRA é escrito no que é chamado “Caixa Alta”, Um TeXtO EscRito DesTa MANeira é chamado “camel case”, muito usado em nomes de rotinas armazenadas (functions & procedures) por exemplo IntToStr, GetFilePath... Outro “charCase” é a caixa baixa, quando o texto é escrito em minúsculas.
Agora nós chegamos ao problema. Para a programação “iTunes” “Itunes” e “itunes” são palavras completamente diferentes, assim como “Ana das Dores” “Ana Das Dores” e “ana das dores”. Logo quando temos um cadastro com o texto “itunes” se buscarmos por “iTunes” o delphi não irá encontrar o texto. Uma solução muito comum, é padronizar a maneira com que o texto é inserido. Isto é feito alterando a propriedade “CharCase” de todos os componentes “DBEdit” no programa.
Neste artigo eu vou ensinar uma maneira de localizar um texto independentemente da maneira com que está escrito. Para isso nó usaremos uma linguagem de programação chamada “Regex” ou “expressões regulares”. O Delphi não tem suporte nativo ao regex (que é mais utilizado na linguagem PERL), por isso nós temos que utilizar um componente chamado TPERLRegEx, ele pode ser encontrado nesse link: http://www.regular-expressions.info/download/TPerlRegEx.zip
Instalando
Depois de fazer o download do componente, extraia o arquivo .zip e abra o arquivo “PerlRegExD7”. Na janela do delphi, clique no botão “Compile” e depois em “Intstall”.
Usando o componente sem banco de dados
Vou fazer primeiro uma abordagem do uso dele sem banco de dados, para depois irmos para a pesquisa em tabelas.
2 - Insira uma LABEL, um LISTBOX, um EDIT, um BUTTON e um PerlRegEx (paleta JGSoft)
3 – No componente PerlRegEx1 vá em “Options” e defina a opção “preCaseLess” como “True”
4 – No componente ListBox1 vá em “Items” e clique nos três pontos. Abrirá uma janela para você editar os itens do listbox. Adicione os items “Itunes” “deLPHI” “mArIa” (usei esses nomes como exemplo, você pode inserir os itens que quiser)
5 – No evento OnClick do componente Button1 coloque o seguinte código:
procedure TForm1.Button1Click(Sender: TObject);
var
i: integer;
begin
PerlRegex1.RegEx := Edit1.Text;
for i:= 0 to ListBox1.Items.Count - 1 do begin
PerlRegex1.Subject := ListBox1.Items.Strings[i];
if PerlRegex1.Match then begin
Label1.Caption := PerlRegex1.Subject;
end;
end;
end;
Explicando o código:
A propriedade “Regex” do componente PerlRegEx1 é o código regex que nós vamos utilizar para procurar. No momento nós não vamos utilizar códigos regex, por isso nós só vamos digitar o texto que queremos encontrar.
A propriedade “Subject” é o texto onde ele vai tentar localizar o código Regex.
A função “Match” faz a busca pelo “Regex” na string “Subject” e retorna true/false no caso do regex ser encontrado no “Subject”.
Testando o Programa
Considerando que os items na listBox sejam “Itunes” “deLPHI” e “mArIa”, digite, por exemplo, “ITUNES” no Edit e clique no botão. O texto da label deverá ser alterado para “Itunes”, isso é um sinal de que o fato do texto que você procura estar escrito de maneira diferente, ele foi encontrado. Agora realize testes com outros itens e outras maneiras de escrever.
Espero que tenham gostado!
Dúvidas: E-mail: bidu.pub@gmail.com orkut: “81duz1d0”
No próximo artigo vou explicar como fazer o mesmo processo num banco de dados.
Regex with delphi (2) - Databases
Hello!
In this article, I’ll talk about using regex with
To do that, I’ll create a folder called “regex” and, inside that, a sub-folder called “data”. In the “regex” folder I’ll save de Delphi project, and inside the “Data” folder a paradox database (I’ll use paradox just for example, you can use anyone).
Creating the table
Open your Database Desktop, click in File -> New -> Table
Create a table with the following features:
Name: Reg1
Fields:
Cod – Type: + - Key: *
Name – Type: A – Size: 255
Save in “Regex/Data”
Open the table in the Database Desktop, and add the following records (please, use the capitalization just like the following):
iPod
Anne
marie
Us
un
As I said in my last article, the regex doesn’t care about de case of the word. If the word is “IPOD” “ipod” “iPod or even “iPoD”, a regex engine will match all of them.
Creating the alias
(If you’re using paradox)
Open the BDE Administrator. Click in the tab “Databases” and then in “Object” -> “New” -> “Standard”
Rename the new alias as “Regex” and in the tab “Definition” (right side of the window) set the following properties:
Path: (the path for the “data” folder, by example C:/regex/data. But it’s critical for system’s work that you set this property right)
Now, click in “Object” -> “Apply” in the confirmation dialog press “ok”.
Making it work!!
Alias ready, table ready, now lets “delphi”. Open your delphi, click in “file” -> “new” -> “application”, click in the “Save All” button and save it on the “regex” folder.
Now add the following components: an edit, a button, a DataSource, a table, a Dbgrid and a PerlRegex (tab JGSoft).
Set the properties:
Now you should see a DBGrid with the records that we put in the Paradox Table.
How to search the table with a component that doesn’t allow database queries? And after the searching, how to show the results?
The solution that I create is to make a “for” conditional loop that moves through the entire table and searches string-by-string, so bigger table <–> slower search.
IMPORTANT: first double-click the table1 a window must appear. Left-click in the window and click in “Add all fields”
procedure TForm1.Button1Click(Sender: TObject);
var
recnum,i: integer;
begin
recnum := Table1.RecordCount;
PerlRegex1.Regex := Edit1.Text;
for i:= 1 to recnum do begin
table1.RecNo := i;
PerlRegex1.Subject := Table1Name.AsString;
PerlRegex1.Match;
end;
end;
Explaining the code
This is a very simple code. The variable “recnum” holds the number of the records in the table. The variable “I” holds the value for the loop (this must be 1 and goes to “recnum”).
“For” it’s a well-known loop, if you have problems to understand it, please email me bidu.pub@gmail.com I’ll be glad to teach you. For every value of I, we’ll set the table current record to I (first line of the loop: table1.RecNo := i;).
PerlRegex “regex” property holds the REGEX code for the search. We won’t use advanced regex statements, but if you know regex you can use. The command “PerlRegex1.Subject := Table1Name.AsString” tells to the regex for make the search in the current record of the table. The “match” function makes the search.
Showing the results!
Well, the search was made lets show the results. Add a ListBox. In the event “OnMatch” from “PerlRegex1” add the following code:
ListBox1.Items.Add(PerlRegex1.Subject);
Simple, easy and fast! If, and only if, the “Regex” was match in “Subject”, the subject is put in the items property of the list box.
Testing
It’s done! Search made, results showed! Now you can make everything that you want with the results.
Well, this small season about regex is over. I hope you liked!
In the next article (article number 3) I’ll talk about connecting
Troubles?
Email me: bidu.pub@gmail.com
Or in orkut: 81duz1d0
Regex no Delphi (2) - Banco de dados
Neste artigo eu vou falar sobre o uso do regex com o Delphi para fazer pesquisa em banco de dados. Para fazer isso eu vou criar uma pasta chamada “regex” e, dentro dela, uma sub-pasta chamada “data”. É obvio o que vou fazer: na pasta “regex” eu vou salvar o projeto do Delphi, e dentro da pasta “data” um banco de dados paradox
Criando a tabela
Crie uma tabela com as seguintes características:
Cod – Type: + - Key: *
Nome – Type: A – Size: 255
Salve em “Regex/Data”
iPod
Ane
marie
Us
un
Como eu disse no meu último artigo, o regex não se importa com a maneira que a palavra está escrita. Se a palavra é “IPOD”, “ipod”, “iPod” ou até mesmo “iPoD”, um mecanismo de regex vai encontrar todas elas
Criando o Alias
(se você está usando paradox)
Abra o BDE Administrator. Clique na aba “Databases” e então em “Object” -> “New” -> “Standard”
Fazendo funcionar!!!
Alias pronto, tabela pronta, agora vamos “delphizar”
Abra o Delphi clique em “file” -> “new” -> “application”, clique em “Save All” e salve na pasta “regex”.
Modifique as propriedades:
DBGrid1: “DataSource” = DataSource1
PerlRegex1: Options/preCaseLess = true
Agora você deverá estar vendo um DBGrid com todos os registros que colocamos na tabela.
Buscando e exibindo
Como buscar numa tabela com um componente que não permite conexões com banco de dados? E após a busca, como, exibir os resultados.
Nós podemos criar um procedimento que cria uma query SQL, mas eu quero fazer este artigo o mais simples de entender possível, então por equanto não lidaremos com queries SQL dinâmicas. Então a questão continua: como exibir os resultados?
Para responder nós precisamos responder à primeira pergunta: Como fazer a busca?
A solução que criei é fazer um loop condicional “for” que se move por toda a tabela e busca string-por-string, então maior tabela <-> busca mais devagar.
IMPORTANTE: primeiro clique 2 vezes na table1 uma janela deverá aperecer. Clique com o botão direito do mouse na janela e clique em “Add all Fields”
Código: Coloque no evento “OnClick” do button1 o código:
procedure TForm1.Button1Click(Sender: TObject);
var
recnum,i: integer;
begin
recnum := Table1.RecordCount;
table1.First;
PerlRegex1.Regex := Edit1.Text;
for i:= 1 to recnum do begin
table1.RecNo := i;
PerlRegex1.Subject := Table1Name.AsString;
PerlRegex1.Match;
end;
end;
Explicando o código
Esse é um código muito simples. A variável “recnum” contém o número de registros na tabela. A variável “i” contém contém o índice do loop (que vai de 1 até “recnum”). “For” é um loop bastante conhecido, se você tem problemas em entendê-lo, por favor me mande um e-mail.
Para todo valor de I, nós definiremos o registro ativo da tabela para “I”. A propriedade “regex” de PerlRegex contém o código REGEX para a busca. Nós não usaremos propriedades avançadas do regex, mas se você conhece pode utilizar. O commando “PerlRegex1.Subject := Table1Name.AsString” manda o regex fazer a busca no cadastro atual da tabela. A função “match” realiza a busca
Exibindo os resultados
A busca foi feita, para exibir os resultados adicione um ListBox e na propriedade “OnMatch” do “PerlRegex1” coloque o seguinte código:
ListBox1.Items.Add(PerlRegex1.Subject);
Se, e apenas se, o “regex” for encontrado em “subject” o subject será adicionado na ListBox.
Missão completada com sucesso
Pronto! Busca feita, resultados exibidos! Agora você pode fazer o que quiser com os resultados.
Bem, essa pequena temporada sobre regex acabou. Eu espero que você tenha gostado. No próximo artigo (número 3) eu vou falar sobre conectar o Delphi com um “web service”, uma conexão simples, apenas enviar e receber dados. E então um artico sobre conexões com autenticação. Para fazer tudo isso eu vou falar sobre o protocolo HTTP e Componentes INDY. Fique pronto(a) para uma diversão bem maior!
Problemas?
Email: bidu.pub@gmail.com
Orkut: 81duz1d0