2004. március 9., kedd
How to access data from two different databases
Problem/Question/Abstract:
Is it possible for access data from two different database such as...
SELECT A.EMP_NAME, B.DEPT_DESC FROM DB1.TB1 A, DB2.TB1 B WHERE
A.EMP_DEPT = B.DEP_KEY
If so how?
Answer:
Yes, this is called a heterogeneous join. An example of this is like:
SELECT DISTINCT c.cust_no, c.state, o.order_no, i.price
FROM ':Local_alias:customer.db' c,
':IB_alias:order' o,
':SYB_alias:lineitem' i
WHERE o.cust_no = c.cust_no and
o.order_no = i.order_no
The first part between the :: is the BDE alias for the database you want to include in the heterogeneous
join.
2004. március 8., hétfő
How to get the bitmap on a hidden TWinControl
Problem/Question/Abstract:
I want to get a bitmap from the Device Context of a TWinControl that is hidden. Is this possible? I know the handle, but GetDC, Canvas.copyrect etc. return the desktop image.
Answer:
procedure TForm1.Button2Click(Sender: TObject);
var
FControlCanvas: TControlCanvas;
FBitmap: TBitmap;
begin
FControlCanvas := TControlCanvas.Create;
try
FControlCanvas.Control := StringGrid1;
FBitmap := TBitmap.Create;
try
FBitmap.Width := FControlCanvas.Control.Width;
FBitmap.Height := FControlCanvas.Control.Height;
FBitmap.Canvas.CopyRect(Rect(0, 0, FBitmap.Width, FBitmap.Height), FControlCanvas,
Rect(0, 0, FBitmap.Width, FBitmap.Height));
Image1.Picture.Assign(FBitmap);
finally
FBitmap.Free;
end;
finally
FControlCanvas.Free;
end;
end;
2004. március 7., vasárnap
Search for text in a TListView item
Problem/Question/Abstract:
How to search for text in a TListView item
Answer:
Parameters:
lv:
The listview, supposed to be in vaReport mode
S:
The text to search for
Column:
The column index for the column to search , 0-based. Returns the found listview item,
or Nil if none was found
Precondition:
lv <> nil, lv in report mode if column > 0, S not empty
Description:
The search is case-insensitive and will only match on the complete column content. Use
AnsiContainsText instead of AnsiCompareText to match on a substring in the columns content.
function FindListviewItem(lv: TListview; const S: string; column: Integer): TListItem;
var
i: Integer;
found: Boolean;
begin
Assert(Assigned(lv));
Assert((lv.viewstyle = vaReport) or (column = 0));
Assert(S <> '');
for i := 0 to lv.items.count - 1 do
begin
result := lv.Items[i];
if column = 0 then
found := AnsiCompareText(result.caption, S) = 0
else if column <= result.subitems.count then
found := AnsiCompareText(result.subitems[column - 1], S) = 0
else
found := false;
if found then
Exit;
end;
{No hit if we get here}
Result := nil;
end;
2004. március 6., szombat
How to print a TTreeView
Problem/Question/Abstract:
How to print a TTreeView
Answer:
var
bmp: TBitmap;
begin
bmp := TBitmap.Create;
try
bmp.width := treeview.width;
bmp.height := treeview.height;
bmp.canvas.lock;
try
treeview.perform(WM_PRINT, bmp.canvas.handle, PRF_CHILDREN or
PRF_CLIENT or PRF_NONCLIENT);
finally
bmp.canvas.unlock;
end;
{ ... print the bitmap as device-independent bitmap }
finally
bmp.free
end;
end;
Drawing directly to the printer canvas is probably possible but you have to mess with mapping modes, scale the printer canvas, move its origin and so on, the above may be easier to code, especially if you already have a PrintBitmap routine flying around somewhere.
2004. március 5., péntek
How to find a window by its (partial) title and close it
Problem/Question/Abstract:
How can I close an unwanted popup window using its partial title? I have tried destroywindow, however, it cannot close the window I want to close.
Answer:
Well, first you need to get a handle to the window. The following code can find a window by window title (even a partial title, and is case insensisitive) .
function HWndGet(partialTitle: string): hWnd;
var
hWndTemp: hWnd;
iLenText: Integer;
cTitletemp: array[0..254] of Char;
sTitleTemp: string;
begin
hWndTemp := FindWindow(nil, nil);
{Find first window and loop through all subsequent windows in the master window list}
while hWndTemp <> 0 do
begin
{Retrieve caption text from current window}
iLenText := GetWindowText(hWndTemp, cTitletemp, 255);
sTitleTemp := cTitletemp;
sTitleTemp := UpperCase(copy(sTitleTemp, 1, iLenText));
{Clean up the return string, preparing for case insensitive comparison.
Use appropriate method to determine if the current window's caption either
starts with or contains passed string}
partialTitle := UpperCase(partialTitle);
if pos(partialTitle, sTitleTemp) <> 0 then
break;
{Get next window in master window list and continue}
hWndTemp := GetWindow(hWndTemp, GW_HWNDNEXT);
end;
result := hWndTemp;
end;
Once you have the handle you then send the window a WM_CLOSE or WM_QUIT message.
For example:
var
theHandle: THandle;
begin
theHandle := HWndGet('Apps Title');
if theHandle <> 0 then
SendMessage(theHandle, WM_CLOSE, 0, 0);
{ or SendMessage(theHandle, WM_QUIT, 0, 0); }
end;
2004. március 4., csütörtök
Refocus a cell in a TStringGrid
Problem/Question/Abstract:
I have a stringgrid which displays spreadsheet type figures for a year. When the user double clicks a cell then I take the value from one of the cells in that same row and bring up another DB based form so the user can work on data for that record. Now when they have finished editing that record, I need to repopulate the stringgrid, which could (and probably will) put the initial row in a different position. This now leaves a couple of problems: 1. I have a highlighted cell which doesn't correspond to anything. 2. The user doesn't know immediately which item they have just been working on. How can I search the string grid for the item that was initially selected (one of the cells in the selected row holds the primary key value)? When this row is found, I then need to highlight the first column of that row. Is the above possible? I can't seem to see any properties to achieve it.
Answer:
Maybe this helps:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids;
type
TForm1 = class(TForm)
StringGrid1: TStringGrid;
procedure StringGrid1DblClick(Sender: TObject);
procedure StringGrid1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
{Private declarations}
public
{Public declarations}
CurRow: integer;
CurCol: integer;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.StringGrid1DblClick(Sender: TObject);
begin
ShowMessage('Moving the topleft cell');
{Select the upper left cell}
with StringGrid1 do
begin
Row := 1;
Col := 1;
end;
{Process all pending messages}
Application.ProcessMessages;
{Wait 3 seconds}
Sleep(3000);
{Select the previously selected cell}
with StringGrid1 do
begin
Row := CurRow;
Col := CurCol;
end;
Application.ProcessMessages;
end;
procedure TForm1.StringGrid1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
{Remember the selected row and column}
CurRow := StringGrid1.Row;
CurCol := StringGrid1.Col;
end;
end.
2004. március 3., szerda
Adding published properties to forms and datamodules
Problem/Question/Abstract:
When I add published properties to a form / datamodule decendent, what don't I see them is the object inspector?
Answer:
In order to see properties of decendent forms / datamodules in the object inspector, we need three actions:
1. Define the property as published, with a type the object inspector can handle. Note that the object inspector does not handle interface types (in delphi 5).
TMyForm = class(TForm)
published
property MyProp: Integer;
end;
2. Add a register procedure to some unit ( I recomend another unit, that will be included only in design-time package ).
// for TForm decendents:
procedure Register;
begin
RegisterNoIcon([TMyForm]);
RegisterCustomModule(TMyForm,
TCustomModule);
end;
// for TDataModule decendents:
procedure Register;
begin
RegisterNoIcon([TMyForm]);
RegisterCustomModule(TMyForm,
TDataModuleDesignerCustomModule);
end;
the class TDataModuleDesignerCustomModule is in the DMDesigner unit, for which we have no source. The unit is in the dsnide50.bpl. In order to use this unit we have to include the dsnide50.bpl package in our's package 'Requires'. As this package is used only by the delphi IDE, I recommend to add it only to a design-time packages.
3. Compile and install the new package. Now we will see the new property in the object inspector.
2004. március 2., kedd
How to convert a string to DateTime using a format mask
Problem/Question/Abstract:
How to convert a string to DateTime using a format mask
Answer:
unit FileNameRoutines2;
interface
{DATE-TIME NAME CONVERTER OBJ}
type
tDateTimeNameConverterObj = class
private
fDefiningTemplate: string;
fOpnBrk,
fClsBrk: char;
fSearchTemplate: string;
fConstructionTemplate: string;
NYrC: integer;
YrCs: array[0..3] of integer; {Indexes w/in constr template.}
NMoC: integer;
MoCs: array[0..3] of integer;
NDaC: integer;
DaCs: array[0..3] of integer;
NHrC: integer;
HrCs: array[0..3] of integer;
NMiC: integer;
MiCs: array[0..3] of integer;
NSeC: integer;
SeCs: array[0..3] of integer;
public
constructor CreateFromDateTimeNameTemplate(const aBrackets, aDateTimeNameTemp:
string);
property DefiningTemplate: string read fDefiningTemplate;
property SearchTemplate: string read fSearchTemplate;
property ConstructionTemplate: string read fConstructionTemplate;
function DateTimeToName(aDateTime: tDateTime): string;
function NameToDateTime(const aName: string): tDateTime;
function IsValidDateTimeName(const aName: string; var aDateTime: tDateTime):
integer;
end;
type
tDateTimeNameConverterObj2 = class
private
fDefiningTemplate: string;
fOpnBrk,
fClsBrk: char;
fSearchTemplate: string;
fConstructionTemplate: string;
NYrC: integer;
YrCs: array[0..3] of integer; {Indexes w/in constr template.}
NMoC: integer;
MoCs: array[0..3] of integer;
NDaC: integer;
DaCs: array[0..3] of integer;
NHrC: integer;
HrCs: array[0..3] of integer;
NMiC: integer;
MiCs: array[0..3] of integer;
NSeC: integer;
SeCs: array[0..3] of integer;
procedure SetDefiningTemplate(const aDefiningTemplate: string);
public
constructor Create(const aBrackets: string);
property DefiningTemplate: string read fDefiningTemplate write
SetDefiningTemplate;
property SearchTemplate: string read fSearchTemplate;
property ConstructionTemplate: string read fConstructionTemplate;
function DateTimeToName(aDateTime: tDateTime): string;
function NameToDateTime(const aName: string): tDateTime;
function IsValidDateTimeName(const aName: string; var aDateTime: tDateTime):
integer;
end;
implementation
uses
SysUtils;
{ tDateTimeNameConverterObj }
constructor tDateTimeNameConverterObj.CreateFromDateTimeNameTemplate
(const aBrackets, aDateTimeNameTemp: string);
var
c: char;
i: integer;
InDate: boolean;
begin
fOpnBrk := aBrackets[1];
fClsBrk := aBrackets[2];
fDefiningTemplate := aDateTimeNameTemp;
fConstructionTemplate := '';
InDate := false;
for i := 1 to length(fDefiningTemplate) do
begin
c := fDefiningTemplate[i];
if not InDate then
if c = fOpnBrk then
begin
InDate := true;
fSearchTemplate := fSearchTemplate + '*';
end
else
begin {copy name characters}
fConstructionTemplate := fConstructionTemplate + c;
fSearchTemplate := fSearchTemplate + c;
end
else
if c = fClsBrk then
InDate := false
else
begin
fConstructionTemplate := fConstructionTemplate + c;
case UpCase(c) of
'Y':
begin
if NYrC < 4 then
YrCs[NYrC] := length(fConstructionTemplate);
Inc(NYrC);
end;
'M':
begin
if NMoC < 4 then
MoCs[NMoC] := length(fConstructionTemplate);
Inc(NMoC);
end;
'D':
begin
if NDaC < 4 then
DaCs[NDaC] := length(fConstructionTemplate);
Inc(NDaC);
end;
'H':
begin
if NHrC < 2 then
HrCs[NHrC] := length(fConstructionTemplate);
Inc(NHrC);
end;
'N':
begin
if NMiC < 2 then
MiCs[NMiC] := length(fConstructionTemplate);
Inc(NMiC);
end;
'S':
begin
if NSeC < 2 then
SeCs[NSeC] := length(fConstructionTemplate);
Inc(NSeC);
end;
end;
end;
end;
if ((NYrC <> 2) and (NYrC <> 4)) or ((NMoC <> 0) and (NMoC <> 2)) or ((NMoC = 0) and
(NDaC < 3)) or ((NMoC <> 0) and (NDaC <> 0) and (NDaC <> 2)) or ((NHrC <> 0) and
(NHrC <> 2)) or ((NMiC <> 0) and (NMiC <> 2)) or ((NSeC <> 0) and (NSeC <> 2))
then
raise Exception.Create(Format('Bad date template (%d, %d, %d, %d, %d, %d)',
[NYrC, NMoC, NDaC, NHrC, NMiC, NSeC]));
end;
function tDateTimeNameConverterObj.IsValidDateTimeName(const aName: string;
var aDateTime: tDateTime): integer;
procedure XX(i: integer; var n: word);
var
c: Char;
begin
c := aName[i];
if c in ['0'..'9'] then
n := 10 * n + (ord(c) - ord('0'))
else
Result := i;
end;
var
i: Integer;
y, y2, y0, m, m2, d, d2, h, n, s: Word;
begin
y := 0;
m := 0;
d := 0;
h := 0;
n := 0;
s := 0;
for i := 0 to NYrC - 1 do
XX(YrCs[i], y);
for i := 0 to NMoC - 1 do
XX(MoCs[i], m);
for i := 0 to NDaC - 1 do
XX(DaCs[i], d);
for i := 0 to NHrC - 1 do
XX(HrCs[i], h);
for i := 0 to NMiC - 1 do
XX(MiCs[i], n);
for i := 0 to NSeC - 1 do
XX(SeCs[i], s);
if m = 0 then
m := 1;
if d = 0 then
d := 1;
try
if NYrC = 2 then
begin {do the Y100 stuff}
DecodeDate({Current} Date, y2, m2, d2);
y0 := 100 * (y2 div 100);
y := y + y0;
if y < y2 - 50 then
y := y + 100;
end;
aDateTime := EncodeDate(y, m, d) + EncodeTime(h, n, s, 0);
Result := 0;
except
on Exception do
aDateTime := 0;
end;
end;
function tDateTimeNameConverterObj.NameToDateTime(const aName: string): tDateTime;
begin
if IsValidDateTimeName(aName, Result) <> 0 then
raise Exception.Create('Filename (' + aName + ') does not contain valid date.');
end;
function tDateTimeNameConverterObj.DateTimeToName(aDateTime: tDateTime): string;
var
Y, M, D, H, N, S, X: Word;
str: string[5];
i: integer;
begin
Result := fConstructionTemplate;
DecodeDate(aDateTime, Y, M, D);
DecodeTime(aDateTime, H, N, S, X);
str := IntToStr(10000 + Y);
for i := 0 to NYrC - 1 do
Result[YrCs[i]] := str[i + 6 - NYrC];
str := IntToStr(10000 + M);
for i := 0 to NMoC - 1 do
Result[MoCs[i]] := str[i + 6 - NMoC];
str := IntToStr(10000 + D);
for i := 0 to NDaC - 1 do
Result[DaCs[i]] := str[i + 6 - NDaC];
str := IntToStr(10000 + H);
for i := 0 to NHrC - 1 do
Result[HrCs[i]] := str[i + 6 - NHrC];
str := IntToStr(10000 + N);
for i := 0 to NMiC - 1 do
Result[MiCs[i]] := str[i + 6 - NMiC];
str := IntToStr(10000 + S);
for i := 0 to NSeC - 1 do
Result[SeCs[i]] := str[i + 6 - NSeC];
end;
{ tDateTimeNameConverterObj2 }
constructor tDateTimeNameConverterObj2.Create(const aBrackets: string);
begin
fOpnBrk := aBrackets[1];
fClsBrk := aBrackets[2];
end;
procedure tDateTimeNameConverterObj2.SetDefiningTemplate(const aDefiningTemplate:
string);
var
c: Char;
i: integer;
InDate: boolean;
begin
fDefiningTemplate := aDefiningTemplate;
fConstructionTemplate := '';
fSearchTemplate := '';
fConstructionTemplate := '';
NYrC := 0;
NMoC := 0;
NDaC := 0;
NHrC := 0;
NMiC := 0;
NSeC := 0;
InDate := false;
for i := 1 to length(fDefiningTemplate) do
begin
c := fDefiningTemplate[i];
if not InDate then
if c = fOpnBrk then
begin
InDate := true;
fSearchTemplate := fSearchTemplate + '*';
end
else
begin {copy name characters}
fConstructionTemplate := fConstructionTemplate + c;
fSearchTemplate := fSearchTemplate + c;
end
else if c = fClsBrk then
InDate := false
else
begin
fConstructionTemplate := fConstructionTemplate + c;
case UpCase(c) of
'Y':
begin
if NYrC < 4 then
YrCs[NYrC] := length(fConstructionTemplate);
Inc(NYrC);
end;
'M':
begin
if NMoC < 4 then
MoCs[NMoC] := length(fConstructionTemplate);
Inc(NMoC);
end;
'D':
begin
if NDaC < 4 then
DaCs[NDaC] := length(fConstructionTemplate);
Inc(NDaC);
end;
'H':
begin
if NHrC < 2 then
HrCs[NHrC] := length(fConstructionTemplate);
Inc(NHrC);
end;
'N':
begin
if NMiC < 2 then
MiCs[NMiC] := length(fConstructionTemplate);
Inc(NMiC);
end;
'S':
begin
if NSeC < 2 then
SeCs[NSeC] := length(fConstructionTemplate);
Inc(NSeC);
end;
end;
end;
end;
if ((NYrC <> 2) and (NYrC <> 4)) or ((NMoC <> 0) and (NMoC <> 2)) or ((NMoC = 0) and
(NDaC < 3)) or ((NMoC <> 0) and (NDaC <> 0) and (NDaC <> 2)) or ((NHrC <> 0) and
(NHrC <> 2)) or ((NMiC <> 0) and (NMiC <> 2)) or ((NSeC <> 0) and (NSeC <> 2))
then
raise Exception.Create(Format('Bad date template (%d, %d, %d, %d, %d, %d)',
[NYrC, NMoC, NDaC, NHrC, NMiC, NSeC]));
end;
function tDateTimeNameConverterObj2.IsValidDateTimeName(const aName: string;
var aDateTime: tDateTime): integer;
procedure XX(i: integer; var n: word);
var
c: Char;
begin
c := aName[i];
if c in ['0'..'9'] then
n := 10 * n + (ord(c) - ord('0'))
else
Result := i;
end;
var
i: integer;
y, y2, y0, m, m2, d, d2, h, n, s: Word;
begin
y := 0;
m := 0;
d := 0;
h := 0;
n := 0;
s := 0;
for i := 0 to NYrC - 1 do
XX(YrCs[i], y);
for i := 0 to NMoC - 1 do
XX(MoCs[i], m);
for i := 0 to NDaC - 1 do
XX(DaCs[i], d);
for i := 0 to NHrC - 1 do
XX(HrCs[i], h);
for i := 0 to NMiC - 1 do
XX(MiCs[i], n);
for i := 0 to NSeC - 1 do
XX(SeCs[i], s);
if m = 0 then
m := 1;
if d = 0 then
d := 1;
try
if NYrC = 2 then
begin {do the Y100 stuff}
DecodeDate({Current} Date, y2, m2, d2);
y0 := 100 * (y2 div 100);
y := y + y0;
if y < y2 - 50 then
y := y + 100;
end;
aDateTime := EncodeDate(y, m, d) + EncodeTime(h, n, s, 0);
Result := 0;
except
on Exception do
aDateTime := 0;
end;
end;
function tDateTimeNameConverterObj2.NameToDateTime(const aName: string): tDateTime;
begin
if IsValidDateTimeName(aName, Result) <> 0 then
raise Exception.Create('Filename (' + aName + ') does not contain valid date.');
end;
function tDateTimeNameConverterObj2.DateTimeToName(aDateTime: tDateTime): string;
var
Y, M, D, H, N, S, X: Word;
str: string[5];
i: integer;
begin
Result := fConstructionTemplate;
DecodeDate(aDateTime, Y, M, D);
DecodeTime(aDateTime, H, N, S, X);
str := IntToStr(10000 + Y);
for i := 0 to NYrC - 1 do
Result[YrCs[i]] := str[i + 6 - NYrC];
str := IntToStr(10000 + M);
for i := 0 to NMoC - 1 do
Result[MoCs[i]] := str[i + 6 - NMoC];
str := IntToStr(10000 + D);
for i := 0 to NDaC - 1 do
Result[DaCs[i]] := str[i + 6 - NDaC];
str := IntToStr(10000 + H);
for i := 0 to NHrC - 1 do
Result[HrCs[i]] := str[i + 6 - NHrC];
str := IntToStr(10000 + N);
for i := 0 to NMiC - 1 do
Result[MiCs[i]] := str[i + 6 - NMiC];
str := IntToStr(10000 + S);
for i := 0 to NSeC - 1 do
Result[SeCs[i]] := str[i + 6 - NSeC];
end;
end.
2004. március 1., hétfő
Delete a row in a TStringGrid
Problem/Question/Abstract:
How to delete a row in a TStringGrid
Answer:
procedure TForm1.BitBtn1Click(Sender: TObject);
var
i: Integer;
RowToBeDeleted: Integer;
begin
RowToBeDeleted := 3;
with StringGrid1 do
begin
Rows[RowToBeDeleted].Clear;
for i := RowToBeDeleted to RowCount - 2 do
begin
Rows[i].Assign(Rows[i + 1]);
end;
RowCount := RowCount - 1;
end;
end;
2004. február 29., vasárnap
Determine which application is associated with a specific file name extension
Problem/Question/Abstract:
Determine which application is associated with a specific file name extension
Answer:
To determine which application is associated with a specific file name extension you can look in the registry under HKEY_CLASSES_ROOT.
Easier is to use the Windows API function FindExecutable() - see the following example. The code shows the fully qualified associated application or the last error (using GetLastError).
program Project1;
uses
Forms, Dialogs, ShellAPI, SysUtils, Windows;
{$R *.RES}
var
sApp: array[0..256] of char;
begin
// this should return something like c:\program files\office\excel.exe
if FindExecutable('c:\temp\xxx.xls', nil, sApp) >= 32 then
ShowMessage(sApp)
else
ShowMessage(SysErrorMessage(GetLastError));
end.
2004. február 28., szombat
How to get the number of matches when searching a string
Problem/Question/Abstract:
I want to check how many of the individual characters in a search string are matching a source string. When comparing the strings, each character position should be checked individually. Examples:
Seach string: 'ABC' / Source string: 'ABX' / Result: 2 matching positions
Seach string: 'ABC' / Source string: 'AXB' / Result: 1 matching position
Answer:
Solve 1:
Assuming the compare always starts from the beginnig of the source string, i.e. Search string: 'ABC' and Source string: 'AXAB' returns 1:
function MyStrComp(strSearch, strSource: string): integer;
var
LenSearch, LenSource, Len: integer;
LoopCounter: integer;
begin
LenSearch := length(strSearch);
LenSource := length(strSource);
if LenSearch > LenSource then
Len := LenSource
else
Len := LenSearch;
if Len = 0 then
Result := 0
else
begin
LoopCounter := 1;
repeat
if (strSearch[LoopCounter] <> strSource[LoopCounter] then
break;
Inc(LoopCounter);
until
(LoopCounter > Len);
Result := LoopCounter - 1;
end;
end;
The above function may not be the fastest, but it should be pretty fast. If you are going to call this compare function in a loop and the search string will not change within the loop, find the length of the search string before getting in the loop, then pass it to the compare function as a parameter can save a call to the length function in the compare function.
If you know that the source string is always longer than the search string, you can skip comparing the lengths and use the length of the search string to control your repeat loop.
Solve 2:
From AdvanceStringCore www.excommunicant.co.uk. You may use this routine for non commercial purposes providing appropriate credit is given.
{Concurrent matching char elements}
function ConcurrentCountMatchingCharElements(const SourceChars, MaskChars: string;
const CSensitive: Boolean): Integer;
{Version 1.0 (September 2000 - Lachlan Fairgrieve)
(C)2000 Excommunicant www.excommunicant.co.uk
Returns the number of times [mask[i]] and [source[i]] characters match}
var
{initialise :
validate strings (for length)
Count Lengths
normalise lengths
Prepare Pointers (For case insensitive and standard search)
Source Scan : For Every [Source] Char check against every [mask] char}
NewSource, NewMask: string; {Hold normalised strings}
SourceP, MaskP: PChar;
index: Integer; {Source and Mask index vars}
ScanLength: Integer; {The number of chrs to scan}
begin
{Initialise}
Result := 0;
if SourceChars = '' then
exit;
if MaskChars = '' then
exit;
ScanLength := Length(SourceChars);
if Length(MaskChars) < ScanLength then
ScanLength := Length(MaskChars);
{prepare string pointers}
if not CSensitive then
begin
NewSource := uppercase(SourceChars);
NewMask := uppercase(MaskChars);
SourceP := Pointer(NewSource);
MaskP := Pointer(NewMask);
end
else
begin
SourceP := Pointer(SourceChars);
MaskP := Pointer(MaskChars);
end;
{source scan}
for index := 1 to ScanLength do
begin
if MaskP^ = SourceP^ then
inc(result);
inc(MaskP);
inc(SourceP);
end;
end;
2004. február 27., péntek
Roll up and restore a TForm when clicking on the title bar
Problem/Question/Abstract:
How to roll up and restore a TForm when clicking on the title bar
Answer:
The standard behaviour for double clicking a title bar is to maximize/ restore the form. The following class changes the double click action to add a new effect which is RollUp/ Restore. Copy the following unit and place it in a directory which is recognised by Delphi's search path.
unit OrckaForm;
interface
{$B-}
uses
Messages, Forms, Classes;
type
TOrckaForm = class(TForm)
private
FOldHeight: Longint;
FRollUp, FRolledUp: Boolean;
protected
procedure WMNCLDblClick(var Msg: TMessage); message WM_NCLBUTTONDBLCLK;
procedure WMGetMinMaxInfo(var Msg: TMessage); message WM_GETMINMAXINFO;
public
constructor Create(AOwner: TComponent); override;
property RollUp: Boolean read FRollUp write FRollUp;
end;
implementation
uses
Windows;
procedure TOrckaForm.WMNCLDblClick(var Msg: TMessage);
begin
if (Msg.wParam = HTCAPTION) and (FRollUp) then
begin
if FRolledUp then
begin
FRolledUp := False;
Height := FOldHeight;
end
else
begin
FRolledUp := True;
FOldHeight := Height;
Height := 0
end;
end
else
inherited;
end;
constructor TOrckaForm.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOldHeight := Height;
FRollUp := True;
FRolledUp := False;
end;
procedure TOrckaForm.WMGetMinMaxInfo(var Msg: TMessage);
begin
inherited;
if FRolledUp then
pMinMaxInfo(Msg.lParam)^.ptMaxTrackSize.y := Height;
end;
end.
To use the form create a new form which will look something like..
unit Unit3;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TForm3 = class(TForm)
private
{ Private declarations }
Add OrckaForm to the uses clause and change the following line
TForm3 = class(TForm)
to
TForm3 = class(TOrckaForm)
Run your project, whenever you double click the title the form will roll up/ restore.
2004. február 26., csütörtök
Search for shared folders in a network
Problem/Question/Abstract:
How to search for shared folders in a network
Answer:
You will need a listbox, a radiogroup with 3 radio buttons and of course a button. It takes a while depending on the size of your network.
procedure TForm1.EnumNetResources(List: TStrings);
procedure EnumFunc(NetResource: PNetResource);
var
Enum: THandle;
Count, BufferSize: DWORD;
Buffer: array[0..16384 div SizeOf(TNetResource)] of TNetResource;
i: Integer;
begin
if WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, NetResource,
Enum) = NO_ERROR then
try
Count := $FFFFFFFF;
BufferSize := SizeOf(Buffer);
while WNetEnumResource(Enum, Count, @Buffer, BufferSize) = NO_ERROR do
for i := 0 to Count - 1 do
begin
case RadioGroup1.ItemIndex of
0:
begin {Network Machines}
if Buffer[i].dwType = RESOURCETYPE_ANY then
List.Add(Buffer[i].lpRemoteName);
end;
1:
begin {Shared Drives}
if Buffer[i].dwType = RESOURCETYPE_DISK then
List.Add(Buffer[i].lpRemoteName);
end;
2:
begin {Printers}
if Buffer[i].dwType = RESOURCETYPE_PRINT then
List.Add(Buffer[i].lpRemoteName);
end;
end;
if (Buffer[i].dwUsage and RESOURCEUSAGE_CONTAINER) > 0 then
EnumFunc(@Buffer[i])
end;
finally
WNetCloseEnum(Enum);
end;
end;
begin
EnumFunc(nil);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Listbox1.Clear;
Screen.Cursor := crHourglass;
EnumNetResources(ListBox1.Items);
Screen.Cursor := crDefault;
end;
2004. február 25., szerda
Parsing the Web
Problem/Question/Abstract:
Three Classes for Grabbing HTML/XML Information
Answer:
I recently bought one of the new digital satellite dishes and ran across an interesting challenge - figuring out just what was on, and when. DirectTV provided a Web site with a basic search engine, but the Web-based search was slow and very narrowly focused. As a typical programmer, I knew I could provide a better, more powerful UI, if I could just figure out how their Web search engine worked.
A quick scan of the HTML source pointed out a relatively simple search form that I could easily duplicate, but the HTML results came back in a mildly complicated HTML table. Brute force code would have been simple enough to construct to parse through the table, but I'd been looking for a reason to build a more general parser, so off I went. If I'd known just how lax the HTML rules are, and just how many hacks there are, I'd have just stuck with the brute force method and saved myself a lot of agony, but since I'm here now ...
The Basics
To put together a parser for HTML, an understanding of the rules is required. HTML originated as an SGML-like syntax, and over time has grown to fit more closely within the confines of SGML. These days the syntax is described within an SGML Data Type Definition (DTD) bringing it into a reasonably well-understood and managed domain. Given that SGML now establishes the underpinnings of HTML, the parser should apply the SGML syntax rules as a starting point. This also allows for the consideration of some simple extensions that allow parsing of XML.
Therefore, the parser is built to work on SGML in general, with specific handlers for exceptions and extensions that occur in HTML and XML. The rules for SGML are straightforward, and provide five basic constructs that we care about:
elements,
attributes,
comments,
SGML directives, and
"everything else"
Elements are the facet of the SGML content with which we are most concerned, and around which the parser is established. Elements have a start tag, content, and an end tag, for example:
<TITLE>HTML Parsing</TITLE>
where TITLE is considered to be the "name" of the tag. Element names are case-insensitive. So we start with the following parsing rules:
Element start and end tags are surrounded by < and > characters.
Element end tags are denoted by the / character immediately following a <.
Element content is surrounded by start and end tags.
HTML Extensions
In HTML, we immediately note that there are exceptions to these rules. For some elements - most notably <P> - the end tags may be omitted, even though the element may have contents. This offers perhaps the most annoying challenge of the HTML parsing rule set, because there are several methods by which the element may be terminated.
To start with, we note another syntax rule from SGML: elements may not span. That is, if an element's start tag is contained within another element's start and end tags, its end tag must also appear there. Put simply, if we encounter an end tag, all omitted end tags are considered "closed" back up to the matching start tag. Also, by observation (I couldn't find a formal rule for this in the HTML specification), virtually all elements with optional end tags close when they encounter another of themselves, <LI> and <OPTION> being fine examples. Further, the HTML reference material does indicate that <P> elements that omit their end tags are terminated by "block elements." The HTML DTD must be consulted to determine which elements are considered block elements. Unfortunately, all of this prevents us from using a general rule, and requires that we become concerned with the HTML DTD.
A quick consideration of the DTD is therefore in order. The DTD calls out which elements must have end tags, and which may omit (or are forbidden to have) end tags. For example, the DTD fragment for <P> is:
<!ELEMENT P - O (%inline;)* >
The important thing to note here is - O. The - indicates the start tag is required, and O means the end tag may be omitted. Compare this to the fragment for <BR>:
<!ELEMENT BR - O EMPTY >
where - O EMPTY indicates that the start tag is required. Since the element is EMPTY, however, the optional end tag is now expressly forbidden. In the fragment for <P>, the (%inline;)* shows the legal contents of the P element. In this case, %inline; refers to a list of elements defined earlier in the DTD. Notably missing from the %inline; list is <P> itself. A perusal of the other ambiguous elements reinforces the observation that in general, an element may not immediately contain itself (although this ambitiously general rule is certainly not guaranteed to remain valid for future releases of the HTML DTD). In the same way that %inline; is defined, so there exists a list name %block; which contains the list of block elements.
This leads to another set of parsing rules:
<P> with an omitted end tag is terminated when a block element is encountered.
Elements are terminated when another element of the same name is encountered.
Elements are terminated if a parent's end tag is encountered; no spans are allowed.
Attributes
Attributes represent the various properties of elements. By definition, attributes appear in name/value pairs within the start tag of the element. For example, in:
<BODY bgcolor="#FFFFFF">
the BODY element has an attribute name bgcolor, and the attribute has a value of #FFFFFF. Double quotation marks or single quotation marks are required to delimit the value, unless the value contains only letters, digits, hyphens, and periods. If the value contains single quotation marks, it should be delimited with double quotation marks, and vice versa. Attribute names are case-insensitive. Also worth noting is that not all attributes have a value. For instance, the NOWRAP attribute of the <TD> element.
Attributes appear within an element's start tag
Attributes are delimited by a space character (ASCII 32)
Attribute values are delimited by " or '
Comments
SGML also provides that its content may include comments. Comments are of the form:
<!-- This is a comment -->
The <! is a markup declaration open delimiter, and indicates that an SGML directive is to follow. Comments are specifically denoted by -- following the open delimiter (white space is not allowed between the <! and the --, but is allowed between the closing -- and >). Further, a comment may contain < and > characters. Comments may not include other comments.
<!-- indicates a comment; --> terminates a comment.
< and > are ignored while parsing a comment.
The remaining SGML directives are denoted by the beginning markup declaration open delimiter <!. To further complicate things, comments may exist within the directives delimited by --.
<! denotes an SGML directive (if it's not a comment)
Comments within the directives are delimited by --
Lastly, we consider what remains. Content of elements not contained within a start tag, end tag, or comment is considered by the parser to be PCData (parsed character data).
Store text not included in element start/end tags or comments as PCData.
XML Extensions
As mentioned before, XML is also derived from SGML. While HTML is basically a DTD described within and using SGML, XML is a subset of SGML capable both of representing data and containing other DTDs of its own. XML also demonstrates that those working on the standards in the programming community actually do learn from the mistakes of those that went before them. For instance, the rules of containment are much more formal in XML than they are in HTML, making parsing a great deal simpler. This means that while a DTD may be included in an XML document for syntax checking purposes, it isn't necessarily required for the actual parsing of the XML content, as it is for HTML.
Knowing this, we can add two more rules and provide DTD-less XML parsing as well. For one, empty elements in HTML are simply called out as such in the DTD with their end tags forbidden (<BR> for example). If an element in XML is to be empty (that is, it will have no content) its start tag may have a / just before the closing > indicating that no content and no end tag will follow. Additionally, XML directives may appear with the ? character rather than !.
Empty elements in XML may be terminated by a / just before the > in the start tag, e.g. <partno/>.
Additional directives appear using ?, instead of the ! character.
Everything Else
Any items encountered in the content that are not contained in element start or end tags, comments, or DTD items are considered by the parser to be PCData. The content of elements fits this bill, as do carriage returns and line feeds encountered by the parser. This leads to the final parsing rule:
Any content located outside of start/end tags, comments, or DTD items is PCData.
Additional Considerations
It is also worth noting that syntax errors and occurrences of "browser-tolerated" HTML inconsistencies are frequently encountered, and as such, should not raise exceptions except in extreme cases. Instead, a warning should be noted and parsing should continue if possible.
The Parser
The goal of parsing the SGML content is to place the data it represents into a form more readily accessible to other components. Since SGML calls out a hierarchical structure a hierarchy is probably the most accurate way to store the parsed content. With that in mind, the parser is built from two primary classes, and a third supporting class.
First and foremost is the THTMLParser class. Its Parse method accepts the content to be parsed, and places the processed results in the Tree property.
Next is the TTagNode class in which the parsed results are contained. This class is a hierarchical storage container with Parent pointing to the TTagNode that contains the current node, and Children containing a list of children immediately owned by the current node.
TTagNodeList is provided as a list container for a collection of TTagNode objects, typically produced by a call to the GetTags method of the TTagNode class.
A Simple Example
Consider the sample HTML shown in Figure 1. The parser would produce from the HTML a hierarchy that can be visualized as in Figure 2. Each of the boxes in the tree represents a TTagNode instance.
<HTML>
<HEAD>
<TITLE>Example HTML</TITLE>
</HEAD>
<BODY>
<!-- Insert non-sensical comment here -->
<H1>Example HTML</H1>
Plain old text right out there in the middle of the document.
<P>Text contained within in paragraph</P>
<B>Unordered List</B>
<UL>
<LI>Item #1
<LI>Item #2
<LI>Item #3
</UL>
</BODY>
</HTML>
Figure 1: Sample HTML.
Figure 2: Hierarchical representation of parsed HTML.
Each node has a NodeType property that indicates what type of node it is. All node types except ntePCData also have text in the Caption property that provides more information about the node's contents. See the table in Figure 3 for details.
Node Contents
NodeType
Caption
HTML elements
nteElement
Element name
Text
ntePCData
Comments
nteComment
!
SGML/XML/DTD directives
nteDTDItem
! or ? and directive
Figure 3: TTagNode node types.
For example, the HTML node in Figure 2 has a NodeType of nteElement, while the comment tag is of type nteComment, and the PCData nodes are of type ntePCData.
The content or text for each HTML element is contained in a node in its Children list. For example, the TITLE node in Figure 2 has a PCData node whose Text property contains "Example HTML". The GetPCData method of a TTagNode returns the PCData text for all children of the node for which it's called. Note, this method is recursive and will return the PCData text for all nodes in the tree beneath the node upon which it's called.
Retrieving Elements
The GetTags method of a TTagNode will return a list of all children that match an element name. If '*' or '' is specified as the element name, then all children will be returned. Note that this method is recursive. The result list is a TTagNodeList.
The code in Figure 4 illustrates how the GetTags method is used to collect a list of all <LI> elements in the HTML from Figure 1 and insert their contents into a list box. The process is as follows:
Create a container for the results, i.e. the Elements list.
Call the GetTags method, passing the desired element name and the container.
Iterate through the container, placing the text for each element in a list box.
Destroy the container.
procedure Button1OnClick(Sender: TObject);
var
Elements: TTagNodeList;
Counter: Integer;
begin
Elements := TTagNodeList.Create;
HTMLParser1.Tree.GetTags('LI', Elements);
for Counter := 0 to Elements.Count - 1 do
ListBox1.Items.Add(Elements[Counter].GetPCData);
Elements.Free;
end;
Figure 4: Using GetTags.
TTagNodeList has two methods that offer another approach (assuming that a result set has already been acquired): GetTagCount and FindTagByIndex. GetTagCount returns a count of the occurrences of an element name. FindTagByIndex returns the index within the list of the specified occurrence of an element name. For instance, the statement:
ShowMessage(Elements.FindTagByIndex('li', 1).GetPCData);
were it included in Figure 4, would display the text for the second occurrence of the <LI> element in the Elements container. This can prove exceptionally useful for locating a specific tag from target HTML content. For example, if the third <TABLE> in the HTML contained the desired data, the following code would make quick work of locating the root <TABLE> node:
HTMLParser1.GetTags('*', Elements);
Node := Elements.FindTagByIndex('table', 2);
if Assigned(Node) then
begin
// Perform processing on <TABLE> node.
end;
Working with Results as a Hierarchy
The procedure in Figure 5 provides yet another method for accessing the contents of the Tree (albeit a more brute force approach). In this example, the HTML content is assumed to be fairly straightforward: <TABLE> elements contain <TR> elements, which contain <TH> and <TD> elements. Given this reasonably accurate assumption, the code will walk the children of a <TABLE> node, and for each <TR> node found will walk its children looking for occurrences of either <TH> or <TR>, and add their text (contained in PCData nodes) to a TStrings container, e.g. the Lines property of a TMemo control.
// Return TableNode's contents in a TStrings container.
procedure GetTable(TableNode: TTagNode; Lines: TStrings);
var
RowCtr,
DataCtr: Integer;
Node,
RowNode: TTagNode;
TempStr: string;
begin
Lines.Clear;
if CompareText(TableNode.Caption, 'table') = 0 then
begin
for RowCtr := 0 to TableNode.ChildCount - 1 do
begin
RowNode := TableNode.Children[RowCtr];
if CompareText(RowNode.Caption, 'tr') = 0 then
begin
TempStr := '';
for DataCtr := 0 to RowNode.ChildCount - 1 do
begin
Node := RowNode.Children[DataCtr];
if CompareText(Node.Caption, 'td') = 0 then
TempStr := TempStr + Node.GetPCData + #9
else if CompareText(Node.Caption, 'th') = 0 then
TempStr := TempStr + Node.GetPCData + #9;
end;
TempStr := Trim(TempStr);
if TempStr <> '' then
Lines.Add(TempStr);
end;
end;
end;
end;
Figure 5: Working with results as a hierarchy.
As an illustration of just how difficult HTML processing can be, the following caveats apply to the code provided in Figure 5 and would have to be handled to provide a robust solution:
Subtables are not handled. That is, <TABLE> elements encountered within a <TD> element are ignored.
Row and column spanning is not handled.
<TBODY>, <THEAD> and a host of other table elements are not considered (although admittedly they are rare).
Working with Results as a List
The procedure in Figure 6 demonstrates working with the parsed results as a list. The goal here is to retrieve a list of all comments, links, meta tags, and images from the document, with the <TITLE> thrown in for good measure. The code does this in several simple steps:
Parse the HTML.
Create a container for the list of matching nodes from the tree.
Call the GetTags method passing '*', and the container ('*' indicates that all items in the tree should be returned).
Iterate through the container collecting matches and place their contents in the StringList.
Destroy the container.
procedure TForm1.Parse(HTML: string; Lines: TStrings);
const
cKnownTags = '|title|img |a |meta |! ';
cTITLE = 0;
cIMG = 1;
cA = 2;
cMETA = 3;
cComment = 4;
var
Index,
Counter: Integer;
TempStr: string;
Nodes: TTagNodeList;
begin
HTMLParser1.Parse(HTML);
Nodes := TTagNodeList.Create;
// Retrieve all nodes.
HTMLParser1.Tree.GetTags('*', Nodes);
for Counter := 0 to Nodes.Count - 1 do
begin
TempStr := '|' + LowerCase(Nodes[Counter].Caption);
// Index of element name.
Index := Pos(TempStr, cKnownTags);
if Index > 0 then
begin
Index := Index div 6;
case Index of
cTITLE:
Lines.Add('Title=' +
HTMLDecode(Nodes[Counter].GetPCData));
cIMG:
begin
TempStr := Nodes[Counter].Params.Values['src'];
if TempStr <> '' then
Lines.Add(
Nodes[Counter].Params.Values['src']);
end;
cA:
begin
TempStr :=
Nodes[Counter].Params.Values['href'];
if TempStr <> '' then
Lines.Add(TempStr + '=' +
HTMLDecode(Nodes[Counter].GetPCData));
end;
cMETA:
with Nodes[Counter].Params do
Lines.Add(Values['name'] + '=' +
Values['content']);
cComment:
Lines.Add('[Comment] ' +
HTMLDecode(Nodes[Counter].Text));
end; { case Index }
end; { if Index > 0 }
end; { for Counter := 0 to Nodes.Count - 1 }
Nodes.Free;
end;
Figure 6: Working with results as a list.
The important thing to understand here is that the TTagNodeList class is just a list of pointers to nodes from the Tree. This is quite beneficial in that once a desired node is located in the list, it may be used as if it had been acquired by traversing the tree. For example, when the case statement in Figure 6 encounters a TITLE element, its contents are retrieved by making a call to the TITLE node's GetPCData method (which depends on the parsed tree structure behaving as it appears to in Figure 2). Note that the PCData often contains encoded items such as > and < (< and > respectively). HTMLDecode is provided for handling most simple cases, but doesn't handle all cases (notably non-US character encoding).
This example also demonstrates the use of the attributes from an element. When an <A> element is encountered, the HREF attribute is examined. If it exists, the <A> element is treated as a link to some other resource. If the HREF attribute were not specified, this might be an instance of <A> serving as an anchor instead of a link. For more details on how the Params property of the TTagNode behaves, see the Delphi help for the Names and Values properties of the TStrings class.
Searching the www.directv.com Program Guide
Applying the HTML parser to the original need turns out to be another simple (albeit involved) exercise. First, an understanding of the CGI scripts that allow searching of the program guide is required. As it turns out, the search script is rather crude and accepts only three parameters: timezone, category, and search text. timezone is simply a number representing Eastern, Central, Mountain, or Pacific. category allows the search to span all programs, or to be narrowed to certain types of programs such as movies or sports. The search text should be all, or a portion of, the desired program name. The search is specific to program names, and doesn't consider program descriptions.
The results of the search are returned as an HTML table including channel, date, time, duration, and program name. The program name is contained within a link to the program description, which will need to be retrieved as well. This is slightly complicated by the fact that the link provided is written using JavaScript which we cannot simply call. However, the URL produced by the JavaScript function is easy to replicate, as it contains a program ID number that can be passed to another CGI script that returns the desired description.
The next step is to parse the HTML and process the results into a more useful format. TStringTable is provided as a simple container for just this purpose. The TStringTable offers a non-visual equivalent to TStringGrid with a few additional methods to make manipulating the data a bit easier. Once the HTML table has been processed and placed in the string table, a bit of house cleaning is required. For one, there are rows at the end of the HTML table that need to be ignored, as they contain images, not program content. Also, the channel appears only in the first row of a set of programs that occur on that channel.
The contents can now be added to a ListView. Once that task is complete, the descriptions can be fetched using the program IDs to call the description CGI, and then added to the ListView.
Further Study
While these examples are not terribly glamorous, the parser can be applied to more meaningful problems. For instance, a friend of mine has put together an extremely handy application using the Pricewatch site (http://www.pricewatch.com/) to monitor prices on PC hardware. Pricewatch offers a current snapshot of pricing of a particular piece of hardware from various vendors, usually sorted from least expensive to most. However, it doesn't allow for viewing of several different pieces of hardware at once, and it doesn't track the history of the price changes for the hardware. So, the application provides a way to build a list of hardware to be tracked, and then offers a simple trend analysis by gathering and saving off the price information on a regular basis. This provides a useful picture for the consumer of just how quickly the prices are moving downward on a particular item. If the pricing is in a steep downward curve, waiting to purchase might be wise. If the curve is flat, the time to purchase might be at hand.
The parser is used not only to retrieve the pricing data, but also to help deal with one of the more significant issues facing those attempting to interface with sites they do not control: unexpected changes in the target site's contents. In this case, a review of the <form> elements from the main page is performed to ensure that the query mechanism remains intact. As a further safeguard, the search results page is also examined to verify a match against the expected HTML format. If unexpected items are found in either case, processing cannot continue, but at least the user can be warned of the situation.
In a more interesting demonstration of the parser's abilities, it has been combined with a database to create a poor man's OODB (object-oriented database). XML is used to wrap the data, and is then stored in text fields in the database. When needed, the XML is retrieved and the parser used to extract the data. Without going in to detail, this is useful because the data stored in the database can carry semantic information with it (the XML elements) that provides information about the data's structure. In systems where the data structure is dynamic, this provides a simple way to avoid excessive database maintenance and further provides a clean, easily understood mechanism for the exchange of data between various applications and platforms. In the case mentioned here, a legacy defect (bug) tracking system hosted on a Solaris platform was wrapped in a Delphi based UI.
Additional Demonstration Applications
To further demonstrate the power of the classes presented in this article, two additional applications accompany this article. An HTML Engine Demo application (see Figure 7) displays a great deal of information about any selected URL, including meta tags, links, and images.
Figure 7: The HTML Engine Demo application.
The Parser Test application parses any URL, or SGML/HTML/XML document, and displays the results in a TreeView (see Figure 8). It can also display links, selected tags, text, etc.
Figure 8: The Parser Test application.
Room for Improvement
This parser builds a reasonable basis for parsing of HTML and XML but, offers significant room for further development.
Incorporation of a DTD processor (DTDs can be parsed with the existing parser, but no handling of the parsed contents is provided). This would provide two main benefits: more thorough parsing of elements based a true understanding of their legal contents and no need for hard coding a representation of the HTML DTD within the parser. Further, DTD-based XML parsing would then be possible.
A DOM container model to complement the TTagNode model. DOM represents a fairly well understood and commonly encountered model for representing the parsed contents of XML. While it doesn't suit all needs, it does provide a useful, standard way to communicate about the parsed elements.
XQL or other suitable extended model query mechanism. The GetTags method is reasonably sufficient, but for more exhaustive queries against XML contents a more advanced mechanism is desired. For example, it would be extremely handy if GetTags could be passed 'order/partno' to indicate that we're searching for all PARTNO elements that are immediately below an ORDER element.
Further performance tuning. While some attention has been paid to this area, no extreme efforts to speed things up were applied. Most notably, Delphi's string routines are not considered to be as fast as those provided in some third-party string-handling collections (notably HyperString).
Resources and Alternatives
For more information and examples, please visit http://www.dallas.net/~richardp/delphi/components/delphicomps.htm.
HTML 4.0 Specification -http://www.w3.org/TR/REC-html40. This is the single most useful resource to those seeking HTML enlightenment. It is extremely detailed and well written.
HTML 4.0 Loose DTD -http://www.w3.org/TR/REC-html40/loose.dtd. A part of the HTML 4.0 specification, this offers the exact specification of just what the HTML rules are. It is upon this DTD (as opposed to the "strict" DTD) that the parser is designer to operate.
"XML: Creating Structures of Meaning," Visual Developer, Nov/Dec 1998, Vol. 9 No. 4. A quick survey of XML for the beginner. Syntax and use are explored here with an eye to bringing the novice on board.
"Using Internet Explorer's HTML Parser," Dr. Dobb's Journal, #302, August 1999 (http://www.ddj.com/articles/1999/9908/9908toc.htm). This article offers an examination of using the HTML parser that is available within Microsoft's Internet Explorer via COM interface. The source for the article is in C++, but it's not difficult to follow.
"XML from Delphi," Delphi Informant Magazine, July 1999, Vol. 5 No. 7. A beginner's explanation of XML, and an excellent example of using the XML parser included in Internet Explorer 4.0.
Begin Listing One - Searching www.directv.com
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, ExtCtrls, GetURL, HTMLMisc,
HTMLParser, StringTable;
type
TForm1 = class(TForm)
WIGetURL1: TWIGetURL;
StatusBar1: TStatusBar;
Panel2: TPanel;
pbSearch: TButton;
ebSearchText: TEdit;
Panel3: TPanel;
ListView1: TListView;
HTMLParser1: THTMLParser;
procedure pbSearchClick(Sender: TObject);
procedure WIGetURL1Status(Sender: TObject;
Status: Integer; StatusInformation: Pointer;
StatusInformationLength: Integer);
private
procedure GetTable(TableNode: TTagNode;
Table: TStringTable);
function GetDescription(Node: TTagNode): string;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
const
cDirecTVSearchURL =
'http:// 206.17.88.15/cgi-bin/pgm_search.cgi/';
cDirecTVDescURL =
'http:// 206.17.88.15/cgi-bin/pgm_desc.cgi/';
// Return TableNode's contents in Table
procedure TForm1.GetTable(TableNode: TTagNode;
Table: TStringTable);
var
RowCtr,
DataCtr: Integer;
Node,
RowNode: TTagNode;
begin
Table.Clear;
if LowerCase(TableNode.Caption) = 'table' then
begin
for RowCtr := 0 to TableNode.ChildCount - 1 do
begin
RowNode := TableNode.Children[RowCtr];
if LowerCase(RowNode.Caption) = 'tr' then
begin
Table.NewRow;
for DataCtr := 0 to RowNode.ChildCount - 1 do
begin
Node := RowNode.Children[DataCtr];
if LowerCase(Node.Caption) = 'td' then
Table.AddColumnObject(Node.GetPCData, Node)
else if LowerCase(Node.Caption) = 'th' then
Table.AddHeader(Node.GetPCData);
end;
if Table.Row[Table.RowCount - 1].Count <= 0 then
Table.DeleteRow(Table.RowCount - 1);
end;
end;
end;
end;
function TForm1.GetDescription(Node: TTagNode): string;
var
TempStr: string;
begin
Result := '';
if Node.ChildCount > 0 then
TempStr := Node.Children[0].Params.Values['href']
else
TempStr := '';
if TempStr <> '' then
begin
// Parse out the description id
Delete(TempStr, 1, Pos('(', TempStr));
Delete(TempStr, Pos(')', TempStr), Length(TempStr));
WIGetURL1.URL := cDirecTVDescURL + TempStr;
Screen.Cursor := crHourglass;
Application.ProcessMessages;
WIGetURL1.GetURL;
Screen.Cursor := crDefault;
StatusBar1.Panels.Items[0].Text := '';
if WIGetURL1.Status = wiSuccess then
begin
TempStr := WIGetURL1.Text;
// Use brute force to scrape out program description.
if Pos('<BLOCKQUOTE>', TempStr) > 0 then
begin
Delete(TempStr, 1, Pos('<BLOCKQUOTE>', TempStr) + 11);
Delete(TempStr, Pos('</BLOCKQUOTE>', TempStr),
Length(TempStr));
end;
Result := TempStr;
end;
end
end;
procedure TForm1.pbSearchClick(Sender: TObject);
const
tzPacific = '0'; // Time zones.
tzMountain = '1';
tzCentral = '2';
tzEastern = '3';
cgMovies = '0'; // Categories.
cgSports = '1';
cgSpecials = '2';
cgSeries = '3';
cgNews = '4';
cgShopping = '5';
cgAllCategories = '-1';
var
Cols,
Rows: Integer;
NewItem: TListItem;
Node: TTagNode;
Nodes: TTagNodeList;
ResultTable: TStringTable;
TempStr: string;
begin
if ebSearchText.Text = '' then
Exit;
WIGetURL1.URL := cDirecTVSearchURL + tzCentral + '/' +
cgAllCategories + '/' + urlEncode(ebSearchText.Text);
Screen.Cursor := crHourglass;
Application.ProcessMessages;
WIGetURL1.GetURL;
Screen.Cursor := crDefault;
StatusBar1.Panels.Items[0].Text := '';
if WIGetURL1.Status = wiSuccess then
begin
if Pos('No program titles that match',
WIGetURL1.Text) > 0 then
ShowMessage('No matches found')
else
begin
// Attempt to parse HTML table we're looking for.
HTMLParser1.Parse(WIGetURL1.Text);
Nodes := TTagNodeList.Create;
HTMLParser1.Tree.GetTags('table', Nodes);
if Nodes.Count > 0 then
begin
ResultTable := TStringTable.Create;
GetTable(Nodes[0], ResultTable);
// Get rid of image tags at bottom of search
// response (the 2nd column has no contents).
with ResultTable do
for Rows := RowCount - 1 downto 0 do
if Cells[1, Rows] = '' then
DeleteRow(Rows);
// Ensure all cells are filled appropriately
// (in the HTML table, a RowSpan attribute
// allows the "Channel" to be displayed in
// one cell for several programs).
with ResultTable do
for Rows := 0 to RowCount - 1 do
for Cols := 0 to ColCount - 1 do
if Cells[Cols, Rows] = '' then
if Rows > 0 then
Cells[Cols, Rows] :=
Cells[Cols, Rows - 1];
// Add items to ListView (Program, Channel,
// Data, Time).
ListView1.Items.Clear;
for Rows := 0 to
ResultTable.RowCount - 1 do
begin
NewItem := ListView1.Items.Add;
NewItem.Caption :=
ResultTable.Cells[4, Rows];
NewItem.SubItems.Add(
ResultTable.Cells[0, Rows]);
NewItem.SubItems.Add(
ResultTable.Cells[1, Rows]);
NewItem.SubItems.Add(
ResultTable.Cells[2, Rows]);
end;
// Retrieve program descriptions (program id
// contained in 4th column's node).
for Rows := 0 to
ResultTable.RowCount - 1 do
begin
// It's rude to whack the server :-)
Sleep(500);
Node :=
TTagNode(ResultTable.Objects[4, Rows]);
TempStr := GetDescription(Node);
ListView1.Items[Rows].
SubItems.Add(TempStr);
end;
ResultTable.Free;
end // if Nodes.Count > 0 ...
else
ShowMessage(
'Error - Expected table...found none');
end; // else of Pos('No program titles that...
end // WIGetURL1.Status = wiSuccess...
else
ShowMessage('Unable to contact search server [' +
WIGetURL1.ErrorMessage + ']');
end;
end.
End Listing One
Component Download: http://www.baltsoft.com/files/dkb/attachment/Parsing_the_Web.zip
Feliratkozás:
Bejegyzések (Atom)