Posts Tagged ‘Delphi’
Delphi http post
Written by Codes Tips on June 2, 2009 – 9:42 am -To post some data through http protocol in Delphi you can use TIDHttp component.
TIDHttp has a function Post that takes 2, first parameter is the url where you wanna post data and the second is the data you need to post.
The first parameter of Post function is a string and the second one is a TStringList.
Delphi sample code to post data through http. First put in the uses clause IdHTTP
function PostData:string; var param:TStringList; valid:boolean; url,text:string; http:TIDHttp; begin http := TIDHttp.Create(nil); http.HandleRedirects := true; http.ReadTimeout := 5000; param:=TStringList.create; param.Clear; param.Add('parameter1=1'); param.Add('parameter2=2'); param.Add('parameter3=3'); valid:=true; url:='http://www.examplesite.com/script.php'; try text:=http.Post(url,param); except on E:Exception do begin valid:=false; end; end; if valid then PostData:= text else PostData := ''; end;
You can call the function like this:
textPostData := PostData();
This function returns empty string if it was an error posting data, if not it returns the text that is returned from the url that we posted data.
We created a new TIDHttp variable at runtime and put the properties ReadTimeout to 5 seconds(timeout of the connection) and HandleRedirects to true, because the url where we post data can redirect us to other page from where we get the result.
Tags: borland delphi, Delphi
Posted in Codes, Delphi | No Comments »
Delphi usefull string functions
Written by Codes Tips on May 10, 2009 – 2:24 pm -This is a list of functions to handle strings in Delphi. It will be update periodically.
Function Stream to String.
If you wanna convert a stream to a string you need to create a TMemoryStream variable and use the function SetString to put the result string
function StreamToString(Stream : TStream) : String; var ms : TMemoryStream; begin Result := ''; ms := TMemoryStream.Create; try ms.LoadFromStream(Stream); SetString(Result,PChar(ms.memory),ms.Size); finally ms.free; end; end;
Function Replace Char
To replace a char with other character you should make a loop until that char is not find in the string. If it is found in the string then replace with the new character. To find position of a character in a string you should use the function pos and return the position in the string where it was found. If it was not found pos returns -1
function ReplaceChar(s:string;c:char;charrep:char):string; begin while pos(c,s)>0 do s[pos(c,s)]:=charrep; ReplaceChar:=s; end;
Function Remove Tags
Function RemoveTags(s:string):string; var k1:integer; s1:string; canwrite:boolean; begin s1:=''; canwrite:=true; for k1:=1 to length(s) do begin if s[k1]='<' then canwrite:=false else if s[k1]='>' then canwrite:=true else begin if canwrite then s1:=s1+s[k1]; end; end; RemoveTags:=s1; end;
Tags: borland delphi, Delphi
Posted in Delphi | No Comments »
Delphi enable and disable proxy in IE
Written by Codes Tips on May 10, 2009 – 2:09 pm -To change the proxy that you connect to internet by code in delphi you need to change the values of 2 fields from the folder settings of Internet Explorer in the registry. Basically you should change the registry values of 2 fields ProxyServer and ProxyEnable. First to use a proxy server you should enable the field ProxyEnable, by setting it to 1. Proxy server is the formatted like server:port and tell the browser through which server should connect.
You should include in the uses cause Registry.
Here is a sample function to change proxy server for internet explorer:
procedure EnableProxy( proxy:string; proxyp:string);
var Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey(’\Software\Microsoft\Windows\CurrentVersion\Internet Settings’, True) then
begin
Reg.WriteString(’ProxyServer’,proxy+’:'+proxyp);
Reg.WriteInteger(’ProxyEnable’,1);
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end;
To disable the proxy by in internet explorer you should set the field ProxyEnable to 0. Here is how to do it:
procedure DisableProxy;
var Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey(’\Software\Microsoft\Windows\CurrentVersion\Internet Settings’, True) then
begin
Reg.WriteInteger(’ProxyEnable’,0);
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end;
Tags: borland delphi, Delphi
Posted in Delphi | No Comments »
Binary search in string array
Written by Codes Tips on May 10, 2009 – 2:04 pm -To search an string into an array of string you can iterate through all the strings one by one and test which is the string that we wanna search. Doing this you will have a complexity of O(n), where n is the number of the strings that array have.
To do search more efficient you should use binary search which have a complexity of O(log2(n)). To use the binary search method in an array of string we assume that we have a sorted array. To sort an array of string efficiently you can use for example Quicksort algorithm , that was previously described, to obtain a good complexity. Of course, you should use binary search algorithm when you are doing something complex that have a complexity bigger or equal to O(n^2).
So to search a string in an array the algorithm selects the middle element of the array and verify if it is equal to our string. If it is equal it stops, if not it sees if the string is bigger then our string and if it is, it searches in the right part of the array string, if not in left part, applying the same algorithm. So it uses a recursive function to search the string in the array.
We will use the following type of string and declare a variable:
type arraystrings=array[1..1000000] of string; var words:arraystrings;
Here is the binary search algorithm:
function BinSearch(word:string;l:integer;h:integer):integer; begin while (StrIComp(pchar(word),pchar(words[(l+h)div 2]))<>0)and(l<>h) do begin if strIcomp(pchar(word),pchar(words[(l+h)div 2]))>0 then l:=(l+h)div 2+1 else h:=(l+h)div 2-1; end; if l<>h then BinSearch:=(l+h)div 2 else BinSearch:=0; end;
It returns the position in the array where it was found. If not returns 0.
To call it you can use:
position:=BinSearch(word,1,nrwords);
where word is the string we search for and nrwords it’s the number of strings in the array.
Tags: Algorithms, Delphi
Posted in Algorithms, Codes, Delphi | No Comments »
Quicksort array of string
Written by Codes Tips on May 10, 2009 – 1:33 pm -Quicksort it’s an algorithm that it’s very efficient when you wanna sort an array of any type: string, integer, real. I will show you how to sort an array of string, it can be modified easily to sort other types of array.
Quicksort it’s efficient because it’s having a sorting complexity of O(n* log2(n)). An usual sorting algorithm like bubble sort or merge sort it’s taking O(n^2), which it’s very inefficient for array with over 5000 elements.
I will write an implementation of this algorithm in Delphi.
The Quicksort algorithm it’s very similar to divide and conquer algorithm because it splits the array into to sub arrays, sort those sub arrays and put them together after into 1 array sorted. For sorting those array it uses a pivot that it’s positioned in the middle of the array and put in the left, strings that are lower and in the right, the strings that are higher. So for doing this it uses a recursive function because for every sub array divides again in 2 sub array and sort them. So after sorting each sub array , we will have in the final step all the array sorted.
Here is an implementation of Quicksort array of string in Delphi.
First declare a type of array string:
type arraystrings=array[1..100000] of string;
Quicksort algorithm:
procedure QuickSort(var A: arraystrings; Lo, Hi: Integer); procedure Sort(l, r: Integer); var i, j,aux: integer; y,x:string; begin i := l; j := r; x := a[(l+r) DIV 2]; repeat while strIcomp(pchar(a[i]),pchar(x))<0 do i := i + 1; while StrIComp(pchar(x),pchar(a[j]))<0 do j := j - 1; if i <= j then begin y := a[i]; a[i] := a[j]; a[j] := y; i := i + 1; j := j - 1; end; until i > j; if l < j then Sort(l, j); if i < r then Sort(i, r); end; begin Sort(Lo,Hi); end;
Tags: Algorithms, Delphi
Posted in Algorithms, Codes, Delphi | 2 Comments »
Delphi ftp upload files directory
Written by Codes Tips on April 25, 2009 – 2:56 pm -To upload files from a directory in delphi to a ftp server you should first loop through all the files that are in that directory. To do this you should first declare a new type of files, that will be a string of array that will hold the names of files from that directory.
type FilesArray=array[1..1000] of string;
To get all the files from a directory you should use the function FindFirst and FindNext to loop through all the files of directory. To use those functions you should include the unit SysUtils in the uses. To get the attribute of a file you should use the record TSearchRec.The TSearchRec record has the following attribute:
type TSearchRec = record Time : Integer; Size : Integer; Attr : Integer; Name : TFileName; ExcludeAttr : Integer; FindHandle : THandle; FindData : TWin32FindData; end;
The most impostant attributes you need are the following:
Time - when the file was last modified
Size - the size of the file
Attr - file attributes
Name - the name of the file
Here is the function to get all the files from a directory:
function GetFiles(dirpath:string;var nrfiles:integer):FilesArray; var searchResult : TSearchRec; allfiles: FilesArray; begin nrfiles:=0; if FindFirst(dirpath+'*.*', faAnyFile, searchResult) = 0 then begin repeat if (searchresult.name<>'.') and (searchresult.name<>'..') then begin inc(nrfiles); allfiles[nrfiles]:=searchresult.name; end; until FindNext(searchResult) <> 0; FindClose(searchResult);//free the memory GetFiles:=allfiles; end; end;
To upload a file to a ftp server we can use the ftp Indy component IdFtp, using the Put command to upload a file. In order not the application to stop when the file is uploaded use a try except statement to catch the error:
procedure UploadFiles(host:string;username:string;password:string); var files:FilesArray; j,nrfiles:integer; idftp1:TIdFtp; begin //conect to ftp server idftp1.Host:=host; idftp1.Username:=username; idftp1.Password:=password; idftp1.Connect; //go in which directory you need with ChangeDir command idftp1.ChangeDir('www'); //get all files from local dir files:=Getfiles(ExtractFilePath(application.exename)+'mydir\',nrfiles); //upload all files from dir to ftp server for j:=1 to nrfiles do begin idftp1.put(ExtractFilePath(application.exename) + 'mydir\' + files[j], files[j]); except On E:Exception do begin end; end; end; //disconnect from ftp server idftp1.Quit; end;
Tags: borland delphi, Delphi
Posted in Codes, Delphi | No Comments »
Remove duplicates from file
Written by Codes Tips on March 27, 2009 – 8:33 am -I will show you how you can remove word duplicates form a file with an efficient algorithm. Say you are having a large file with words that are line by line in a file on your disk. If you want to remove word or phrases duplicates from file you should first read the entire file into an array of strings, sort it and after that remove duplicate phrases and write back to the file.
Why we sort the array?
Because if we would not sort the array of strings then the complexity of a normal algorithm like, taking each phrase and compare to all other phrases, will have the O(N^2) complexity.
Tip: you should use QuickSort algorithm because if you have over 5000 phrases or words, the application will freeze. The complexity of the QuickSort algorithm is O(n*log(n)), so if you have saying 100.000 phrases, the complexity of the QuickSort will be 5000*log(5000) which is lower then 5000*5000, that a normal sorting algorithm uses to sort an array.
After sorting the array you should go through the array from the first phrase to the last element and compare on each step if the previous phrase is equal with the current phrase. If the phrase is not equal we write it to the output file.
This is the description of an efficient remove duplicates phrases algorithm.This function will work even for 1 million phrases or words. Here is the source code of the procedure:
procedure RemoveDuplicates(pathtofile:string); var f:textfile; phrases:array[1..1000000] of string; nr,i,nrduplicates:integer; exists:boolean; s:string; begin nrduplicates:=0; nr:=0; exists:=false; assignfile(f,pathtofile); reset(f); while not eof(f) do begin inc(nr); readln(f,phrases[nr]); end; closefile(f); QuickSort(phrases,1,nr); assignfile(f,pathtofile); rewrite(f); s:=''; for i:=1 to nr do if strIcomp(pchar(s),pchar(phrases[i]))<>0 then begin writeln(f,phrases[i]); s:=phrases[i]; end else inc(nrduplicates); closefile(f); showmessage(inttostr(nrduplicates)+' duplicates removed'); end;
Tags: Algorithms, borland delphi, Delphi
Posted in Algorithms, Codes, Delphi | No Comments »
TIDIRC Tutorial
Written by Codes Tips on March 21, 2009 – 6:47 am -TIDIRC is a component of Indy Client, that can help you connect to an IRC server channel. You can send and receive messages in order to communicate with the server.
There are some important properties which you can use it to specify the server properties:
Host - is the IRC server where you want to connect
Nickname - your nick that will appear in the channel.
ReadTimeout - the time that application should wait until the server don’t respond, it is specified in miliseconds.
RealName - the real name that will appear in the server
Connecting to host
First you should connect to server and you should use the command:
//variable IdIRC1: TIdIRC;// IDIRC1 is a variable of TIDIRC component. //On button click IDIRC1.Connect;
ON succesfull you have an even OnConnected, where you can do something after the connection is established.
After connecting you can receive each response row from the server with the event IdIRCRaw. With this event you have the row AContent which is a string and you can parse it to take the information from the server or other things that you are interested.
You can take the messages that the other users send to the server, get the status of the channel.
Getting Channels
To get a list of channels you should use the property Channels and access the Items property.
for i:=1 to idirc1.Channels.Items.count do List[i] := idirc1.Channels.Items[i];//it's a TIDIRCChannel component
In TIDIRCChannel you will have the list of all channels and for every channel you have properties and events for handling a channel.
Some time, this property will not grab the channels correctly. Here is a function to get the channels from the host. You should put it in the IDIRCRaw event and make a list of channels. This function return a channel:
//GetChannel function function GetChannel(s:string):string; var p1:integer; aux:string; begin p1:=pos('#',s); inc(p1); aux:=''; if p1>1 then while (s[p1]<>' ')and(p1<=length(s)) do begin aux:=aux+s[p1]; inc(p1); end; GetChannel:=aux; end; //calling the channel function channel:=GetChannel(continut); channel:='#'+channel;
Joining a channel
To join a channel on a server you should use the command
IDIRC1.Join(channel);
Sending message
To send a message to one of the users that are connected to the channel
TIDIRC.Say(touser,message)
Parting a channel
TIDIRC.Part(channel,reason)
You can specify an optional string parameter, what was the reason of parting.
Kick user
Other usefull functions for TIDIRC Component:
Thread IRC
IDIRC1.IRCThread.Create(IDIRC1); IDIRC1.IRCThread.Start;
IDIRC1.IRCThread.Terminate; IDIRC1.IRCThread.Free;
Tags: borland delphi, Delphi
Posted in Delphi | No Comments »
Read bigger and small text file delphi
Written by Codes Tips on March 18, 2009 – 10:08 am -Read small text files in Delphi
First we should declare a variable of type TextFile like this
var f:textfile;//defines variable for type TextFile for maintaining data from a file.
We will need also other variables to read the file:
var s:string; ch:char;
If you wanna read contents of a file in Delphi you should first assign to a variable the name of the file you wanna read. You can use the following statement:
assignfile(f,path+'filename.txt');// where path can be the path to the directory
If the file you wanna read it’s inside the folder project then you can use the following code:
path:= ExtractFilePath(application.exename);//ExtractFilePath it's a function that returns a string with the path of an .exe
Next if you should let the compiler know that you wanna read the file.
reset(f);
Now you have more options to read a file depending on what your needs are or how bigger it’s the file from where you read.
You can use the following code to read the file character by character(this version that is not faster to read files):
while not eof(f) do begin read(f,ch); s:=s+ch; end;
You can also use
readln(f,s)
which will read a whole line from the input file.
In the end you should close the file that you opened.
closefile(f);
Complete code, function to return contents of a file:
function ReadSmallFile:string; var freadfile:textfile; s,path:string; ch:char; begin path:= ExtractFilePath(application.exename); assignfile(freadfile,path+'filename.dat'); reset(freadfile); while not eof(freadfile) do begin read(freadfile,ch); s:=s+ch; end; closefile(freadfile); ReadSmallFile:=s; end;
Read bigger file in Delphi
For reading bigger files in Delphi you should use the function BlockRead. This function is used to read blocks of data into a buffer from a file.
To declare a file you should use:
var biggerfile:file of char; BufArray: array[1..4096] of Char;//we will read 4 KB at a time nrcit,i,:integer; sir:string;
You should after assign to a variable just like the type TextFile:
assignfile(biggerfile,path+'namefile.dat'); reset(biggerfile);
Here is a statement to read a bigger file of type char
repeat blockread(biggerfile,BufArray,SizeOf(BufArray),nrcit); for i:=1 to nrcit do sir:=sir+BufArray[i]; until (nrcit = 0);
To close the file you should use
closefile(fis);
Here is a complete source code function to read a bigger file:
function ReadBiggerFile:string; var biggerfile:file of char; BufArray: array[1..4096] of Char;//we will read 4 KB at a time nrcit,i:integer; sir,path:string; begin path:= ExtractFilePath(application.exename); assignfile(biggerfile,path+'namefile.dat'); reset(biggerfile); repeat blockread(biggerfile,BufArray,SizeOf(BufArray),nrcit); for i:=1 to nrcit do sir:=sir+BufArray[i]; until (nrcit = 0); closefile(biggerfile); ReadBiggerFile:=sir; end;
Tags: borland delphi, Delphi, programming
Posted in Delphi | No Comments »
Debugger Exception Notification - project raised exception on try except statement
Written by Codes Tips on March 1, 2009 – 10:20 am -If you want to catch an exception with the try except statement sometimes you can get an error like “Project .exe raised exception … with message …“. This is because delphi is setup to stop on delphi exception when you try to catch the exception. To pass this problem you have to deselect the option for stopping on delphi exception on the Debugger option. To do so, go to Tools -> Debugger Options , after that select the Language Exceptions panel and make sure you deselect the Stop on Delphi Exceptions option. Rebuild again and the problem should be solved.
Tags: borland delphi, Delphi
Posted in Delphi | No Comments »


















