Pressing Buttons on a web page via Delphi [duplicate] - delphi

This question already has answers here:
How to find a button with "value" in html page (Webbrowser - Delphi)
(2 answers)
Closed 8 years ago.
Ex1: WebBrowser.OleObject.Document.GetElementByID('ID HERE').Click;
Ex2: < input type="submit" VALUE="Login" >
The above two examples are for pressing buttons on web pages via Delphi. Ex2 works well on various web sites but not all. Is this because Ex2 only works on HTML buttons? I tried Ex1 but some code is missing, when I try it, I get a message saying 'Object or class type required'. Also Ex1 has no example code, can anyone fill me in on why I get this message and put some code up for Ex1 please.

I got this code from: MrBaseball34 at delphipages
It didn't work initially because I wrote 'WebBrowser' instead of 'WebBrowser1'. But it works perfectly.
Here is the code:
procedure TForm1.Button1Click(Sender: TObject);
var
x: integer;
thelink: OleVariant;
begin
thelink:= WebBrowser1.OleObject.Document.all.tags('A');
if thelink.Length > 0 then
begin
for x := 0 to thelink.Length-1 do
begin
if Pos('put id string here', thelink.Item(x).id) > 0 then
begin
thelink.Item(x).click;
Break;
end;
end;
end;
end;

When working with TWebBrowser, and COM/ActiveX objects in general, it's really handy to know the difference between late binding and early binding. If you use OleVariant variables, have them refer to 'live' object, and use the dot operator (.) to invoke methods and properties, they get resolved at run-time. They are late bound as opposed to early binding where you would use specific interfaces.
Include unit MSHTML in the uses clause, and then use IHTMLDocument3(WebBrowser1.Document), and the different interfaces defined by MSHTML, such as IHTMLElementand IHTMLAnchorElement. You will find that you also get code completion up to some point, but also that you might need an extra cast between things like IHTMLElement and IHTMLElement2 with the asoperator.

There may be any kind of error. Like misspelled ID or wrong datatype missing interface you hope to use, or lacking some item and returning nil instead.
Problem with long lines like WebBrowser.OleObject.Document.GetElementByID('ID HERE').Click; is that you can hardly tell in which place the error occured. And sometimes it is not easy to check intermediate values and its properties. There are a lot of innate expectations coded in such long lines, and you can hardly detect which one was failed.
When you meet errors in such long lines, you'd better split them at tiny action items - the ol' good divide and conquer principle. Declare few variables and split this long complex line into multiple simplistic ones.
var0 := WebBrowser;
var1 := var0.OleObject;
var2 := var1.Document;
var3 := var2.GetElementByID('ID HERE');
var3.Click;
Tracing this, executing one line a time, you can check which values and data types would be issued at each traversing step.

Related

Why do I get access violations when a control's class name is very, very long?

I subclassed a control in order so I can add a few fields that I need, but now when I create it at runtime I get an Access Violation. Unfortunately this Access Violation doesn't happen at the place where I'm creating the control, and even those I'm building with all debug options enabled (including "Build with debug DCU's") the stack trace doesn't help me at all!
In my attempt to reproduce the error I tried creating a console application, but apparently this error only shows up in a Forms application, and only if my control is actually shown on a form!
Here are the steps to reproduce the error. Create a new VCL Forms application, drop a single button, double-click to create the OnClick handler and write this:
type TWinControl<T,K,W> = class(TWinControl);
procedure TForm3.Button1Click(Sender: TObject);
begin
with TWinControl<TWinControl, TWinControl, TWinControl>.Create(Self) do
begin
Parent := Self;
end;
end;
This successively generates the Access Violation, every time I tried. Only tested this on Delphi 2010 as that's the only version I've got on this computer.
The questions would be:
Is this a known bug in Delphi's Generics?
Is there a workaround for this?
Edit
Here's the link to the QC report: http://qc.embarcadero.com/wc/qcmain.aspx?d=112101
First of all, this has nothing to do with generics, but is a lot more likely to manifest when generics are being used. It turns out there's a buffer overflow bug in TControl.CreateParams. If you look at the code, you'll notice it fills a TCreateParams structure, and especially important, it fills the TCreateParams.WinClassName with the name of the current class (the ClassName). Unfortunately WinClassName is a fixed length buffer of only 64 char's, but that needs to include the NULL-terminator; so effectively a 64 char long ClassName will overflow that buffer!
It can be tested with this code:
TLongWinControlClassName4567890123456789012345678901234567891234 = class(TWinControl)
end;
procedure TForm3.Button1Click(Sender: TObject);
begin
with TLongWinControlClassName4567890123456789012345678901234567891234.Create(Self) do
begin
Parent := Self;
end;
end;
That class name is exactly 64 characters long. Make it one character shorter and the error goes away!
This is a lot more likely to happen when using generics because of the way Delphi constructs the ClassName: it includes the unit name where the parameter type is declared, plus a dot, then the name of the parameter type. For example, the TWinControl<TWinControl, TWinControl, TWinControl> class has the following ClassName:
TWinControl<Controls.TWinControl,Controls.TWinControl,Controls.TWinControl>
That's 75 characters long, over the 63 limit.
Workaround
I adopted a simple error message from the potentially-error-generating class. Something like this, from the constructor:
constructor TWinControl<T, K, W>.Create(aOwner: TComponent);
begin
{$IFOPT D+}
if Length(ClassName) > 63 then raise Exception.Create('The resulting ClassName is too long: ' + ClassName);
{$ENDIF}
inherited;
end;
At least this shows a decent error message that one can immediately act upon.
Later Edit, True Workaround
The previous solution (raising an error) works fine for a non-generic class that has a realy-realy long name; One would very likely be able to shorten it, make it 63 chars or less. That's not the case with generic types: I ran into this problem with a TWinControl descendant that took 2 type parameters, so it was of the form:
TMyControlName<Type1, Type2>
The gnerate ClassName for a concrete type based on this generic type takes the form:
TMyControlName<UnitName1.Type1,UnitName2.Type2>
so it includes 5 identifiers (2x unit identifier + 3x type identifier) + 5 symbols (<.,.>); The average length of those 5 identifiers need to be less then 12 chars each, or else the total length is over 63: 5x12+5 = 65. Using only 11-12 characters per identifier is very little and goes against best practices (ie: use long descriptive names because keystrokes are free!). Again, in my case, I simply couldn't make my identifiers that short.
Considering how shortening the ClassName is not always possible, I figured I'd attempt removing the cause of the problem (the buffer overflow). Unfortunately that's very difficult because the error originates from TWinControl.CreateParams, at the bottom of the CreateParams hierarchy. We can't NOT call inherited because CreateParams is used all along the inheritance chain to build the window creation parameters. Not calling it would require duplicating all the code in the base TWinControl.CreateParams PLUS all the code in intermediary classes; It would also not be very portable, since any of that code might change with future versions of the VCL (or future version of 3rd party controls we might be subclassing).
The following solution doesn't stop TWinControl.CreateParams from overflowing the buffer, but makes it harmless and then (when the inherited call returns) fixes the problem. I'm using a new record (so I have control over the layout) that includes the original TCreateParams but pads it with lots of space for TWinControl.CreateParams to overflow into. TWinControl.CreateParams overflows all it wants, I then read the complete text and make it so it fits the original bounds of the record also making sure the resulting shortened name is reasonably likely to be unique. I'm including the a HASH of the original ClassName in the WndName to help with the uniqueness issue:
type
TWrappedCreateParamsRecord = record
Orignial: TCreateParams;
SpaceForCreateParamsToSafelyOverflow: array[0..2047] of Char;
end;
procedure TExtraExtraLongWinControlDescendantClassName_0123456789_0123456789_0123456789_0123456789.CreateParams(var Params: TCreateParams);
var Wrapp: TWrappedCreateParamsRecord;
Hashcode: Integer;
HashStr: string;
begin
// Do I need to take special care?
if Length(ClassName) >= Length(Params.WinClassName) then
begin
// Letting the code go through will cause an Access Violation because of the
// Buffer Overflow in TWinControl.CreateParams; Yet we do need to let the
// inherited call go through, or else parent classes don't get the chance
// to manipulate the Params structure. Since we can't fix the root cause (we
// can't stop TWinControl.CreateParams from overflowing), let's make sure the
// overflow will be harmless.
ZeroMemory(#Wrapp, SizeOf(Wrapp));
Move(Params, Wrapp.Orignial, SizeOf(TCreateParams));
// Call the original CreateParams; It'll still overflow, but it'll probably be hurmless since we just
// padded the orginal data structure with a substantial ammount of space.
inherited CreateParams(Wrapp.Orignial);
// The data needs to move back into the "Params" structure, but before we can do that
// we should FIX the overflown buffer. We can't simply trunc it to 64, and we don't want
// the overhead of keeping track of all the variants of this class we might encounter.
// Note: Think of GENERIC classes, where you write this code once, but there might
// be many-many different ClassNames at runtime!
//
// My idea is to FIX this by keeping as much of the original name as possible, but
// including the HASH value of the full name into the window name; If the HASH function
// is any good then the resulting name as a very high probability of being Unique. We'll
// use the default Hash function used for Delphi's generics.
HashCode := TEqualityComparer<string>.Default.GetHashCode(PChar(#Wrapp.Orignial.WinClassName));
HashStr := IntToHex(HashCode, 8);
Move(HashStr[1], Wrapp.Orignial.WinClassName[High(Wrapp.Orignial.WinClassName)-8], 8*SizeOf(Char));
Wrapp.Orignial.WinClassName[High(Wrapp.Orignial.WinClassName)] := #0;
// Move the TCreateParams record back were we've got it from
Move(Wrapp.Orignial, Params, SizeOf(TCreateParams));
end
else
inherited;
end;

How can I show the contents of a TStringList in the debugger?

I want to display the entire content of a TStringList while debugging the application.
Instead I just get pointers. The Flist is showing only the address.
If you are using Delphi 2010 or later, the debugger allows for this using debug visualizers.
For older versions, you can dump the contents of the Text property in the Watch window or using OutputDebugString, but that's difficult to read. You could set up watches for each element of the list, but that's only practical for very short lists.
I would probably use an external logging app like CodeSite or SmartInspect that let you dump the contents of a TStringList in a single call.
Inspect the Text property. It's the concatenated version of the stringlist.
Since i´m using BDS MMVI, i´m using an "ultra clever smart" method for that kind issue, i use it for large xml documents. I start context file editor (very capable free text editor writen in delphi by the way). On the debugger window a just do a FList.SaveToFile('contents.txt'), since context can monitor file modifications i can see whats happening in my xml files.
Sorry for the "clever" joke but it does work for me.
Peace
I use the visualizers now that I have D2010. I used to use a function I called CArray that would return an array of strings. If I added CArray(MyStringList) to the watch window, I would be able to examine the contents of the string list. I used to be employed to write VB6 code and I sort of liked the various 'C' functions for converting to a useful type. CArray for stringlists and CArray for ClientDataset fields were mostly useful for debugging.
function CArray(List: TStrings): TStrArray; Overload;
var i,
iCount: Integer;
begin
iCount := List.Count;
SetLength(Result, iCount);
for i := 0 to Pred(iCount) do Result[i] := List[i];
end;
My two cents:
You can evaluate expression list_instance_variable.SaveToFile('temp_file_name.txt') and then examine content of the file in any editor.
To do that you must use this function anywhere in code and turn off optimization (at least in Delphi 7), otherwise object code of SaveToFile would be removed by the linker.

saving delphi routines and memory

This question is about being able to save routines, and being able to select them from a list…. When you select one it knows what to link where etc. Just for understanding. not the actual program
Say I want to create a routine in a Delphi form. And I want to create several different ones. They wont be exactly the same but some might be similar. I want to know how you can save things in Delphi and when you close or terminate the application they will remain remembered when you reopen it. I have no idea where to start and how to work this. Any help would be great. Just a hint or a direction, maybe a website with more info or even examples. I’m going to try to give a simpler description below about how it would look on the form…. Just for the idea and I think if I understand this then it would be enough, or a good start at least.
The form will contain a list box a save button and 4 different edit boxes. Lets say I type in edit1;1 and edit2;2 and edit3;3 and edit4;4. Then click the save button and it remembers these 4 value to each edit box and lets say saves in under the value in the list box of ≔edit1.text + ‘to’ + edit4.text. Hope it makes sense so far and then I type in the edit boxes everything the wrong way around. edit1;4 and edit2;3 and edit3;2 and edit4;1. And click save button and it does that again (≔edit1.text + ‘to’ + edit4.text) into the list box. Then I want to close the application. Open it again and still have this in there and still be able to add more of these odd samples….
Can anyone help me?
Edit question, might make it more clear....
I'm going to place the following elements on the form: 2 listboxes(with each 3 lines, in the first listbox: wood, plastic and glass. in the second listbox: tree,cup,window.)
Now I want to link the correct ones, they are in order here, but what is they were not. In a table or in a memory of the application which is not visible on the form I want to link them.
Then if i were to put two edit boxes on the form as wel and I type in the first one wood or tree, it places the other one in the other edit box. So in a way I suppose you are creating a table which knows which one correcsponds with which but also looksup up when you type in edit box. hope that makes sense
From what you wrote I assume that you already know how to add the values to remember to your list box, so I won't deal with this part here. Starting with this answer, you should already have a clue to what to look at in the delphi help files. Please be aware that I didn't test the example, so there may be typos in it.
To store data in the computers registry, delphi provides you with the unit Registry, which contains a class TRegistry.
TRegistry has all the methods needed to retrieve and store values. Following is a short example without any practical use, just to give you the picture. Please be aware that, like mentioned in the comments, there's plenty of room left for you to optimise it. It would, for example, be better to create the TRegistry object only once and then repeatedly call the methods. And - while this plain old delphi unit I wrote is syntactically valid - you might be better off using a more object-oriented approach, like deriving a new class from TRegistry. Please do also check the documentation for the return values of the methods, as some (like OpenKey) simply return false when they are unable to fulfill your request while others (like ReadString) can throw an execption.
unit Unit1;
interface
uses TRegistry, Windows;
procedure saveStringToRegistry(name : String; value : String);
function readIntegerFromRegistry(name : String) : Integer;
implementation
procedure saveStringToRegistry(name : String; value : String);
var r : TRegistry;
begin
r := TRegistry.Create;
try
r.RootKey := HKEY_CURRENT_USER; // Defined in unit Windows, as well as HKEY_LOCAL_MACHINE and others.
r.OpenKey('Software\Manufacturer Name\Produkt Name\Other\Folders',true); // TRUE allows to create the key if it doesn't already exist
r.WriteString(name,value); //Store the contents of variable 'value' in the entry specified by 'name'
r.CloseKey;
finally
r.Free;
end;
end;
function readIntegerFromRegistry(name : String) : Integer;
var r : TRegistry;
begin
r := TRegistry.Create;
try
r.RootKey := HKEY_LOCAL_MACHINE; // Defined in unit Windows
r.OpenKey('Software\Manufacturer Name\Produkt Name\Other\Folders',false); // FALSE: do not create the key, fail if it doesn't already exist
result := r.ReadInteger(name);
r.CloseKey;
finally
r.Free;
end;
end;
end.
OK, now you could use a for loop in your application to process all the items of your list box and save it to the registry using the procedure above, like this:
for i := 0 to ListBox1.Count -1 do
saveStringToRegistry('Entry' + IntToStr(i),ListBox1.Items[i];
Then, you would probably save the number of items you have (of course you would have to define the procedure saveIntegerToRegistry):
saveIntegerToRegistry('NumberOfEntries',ListBox1.Count);
When you need to reload the data, you could do:
ListBox1.Clear;
for i := 0 to readIntegerFromRegistry('NumberOfEntries') -1 do
ListBox1.Items.Add(readStringFromRegistry('Entry' + IntToStr(i));
OK, it's a very basic example, but should give you pointer in the right direction. It could of course need some exception handling (imagine the user accidently deleted Entry42 from the registry, but NumberOfEntries still says there are 55 entries).

Delphi OLE - How to avoid errors like "The requested member of the collection does not exist"?

I'm automating Word with Delphi, but some times I got an error message:
The requested member of the collection
does not exist
It seems that the Item member of the Styles collection class does not always exist and some times causes the above mentioned error. My workaround is to catch the exception and skip it, but is there anyway to detect it instead of using the try...except block? The problem with the try...except block is that when debugging the raised exception is annoying...
My code example:
var
aWordDoc: _WordDocument
i: Integer;
ovI: OleVariant;
wordStyle: Style;
begin
for i := 1 to aWordDoc.Styles.Count do
begin
ovI := i;
try
wordStyle := aWordDoc.Styles.Item(ovI);
except
Continue;//skip if any error occurred.
end;
//do something with wordStyle
end;
end
If the compiler accepts it, but it sometimes cannot happen to exist, it is probably IDispatch based latebinding. IDispatch objects can be queried. Maybe carefully working yourself up the tree querying every object for the next would work.
You would then roughly be doing what the compiler does, except that that one throws an exception if somethines doesn't exist. (and if the exception comes in from COM, maybe a slightly different code path can test more).
Sorry to have no readily made code.
I get that message when a bookmark that I'm trying to fill from Word doesn't exist so i have a process that checks first, but I'm not sure the same method would work for you.
procedure MergeData(strBookMark, strData : string);
begin
if WinWord.ActiveDocument.Bookmarks.Exists(strBookMark) = True then
WinWord.ActiveDocument.FormFields.Item(strBookMark).Result := strData;
end;
It has nothing to do with the Item function not being there. The Item function does exists, but the index you give seems to be wrong.
See this msdn article.
An invalid index seems really weird, because you are performing a for loop from 1 to Styles.Count. So if there is no Style, you should not enter the loop.
The only plausible explanation I can think of is that while you are in your loop, the Styles.Count changes and you are getting out of bounds. Are you deleting styles in your loop perhaps? Try a loop going from Styles.Count downto 1 or try a While loop, evaluating Styles.Count at every iteration.
Other things I can think of, but are very unlikely:
While assigning I to ovI, it gets converted to an OleString, so Word searches for a style named "I", instead of a Style at I
While assigning I to ovI, something in the conversion goes wrong and it gets in the range of $FFFFFFA5 - $FFFFFFFF, which are constants for Builtin styles.
try checking if it is null or not with a IF statement

AV When using a Procedure from one Component called by another

Im not sure if i have explaned this the best i can but, here we go...
I have 2 Custom components on a form, Which are link together at design time through the IDE. Whenever i call a procedure from on of the Component i get the Access violation,
Access violation at address 0049A614
in module 'Project2.exe'. Read of
address 00000034.
This is a small section of my code
TMyClient = class(TClientSocket)
{...}
end;
and...
TPresence = class(TComponent)
private
ftheClient: TMyClient
public
procedure SetStatus(status: string);
published
property UserName : string read fUserName write fUserName;
property theClient: TMyClient read ftheClient write ftheClient;
end;
procedure TPresence.SetStatus(status: string);
begin
try
***** if theClient = nil then
Exception.Create('theClient is Nil');
except
on e:Exception do
MessageDlg(e.classname+', '+e.message, mtWarning, [mbOK], 0);
end;
{...}
end;
0049A614 is at the *****, and the IDE stops here.
I Have also tried to do the assign at run time with
Presence1.theClient := MyClient1;
with no luck
using procedures from Presence1 or MyClient1 that do not rely on each other work fine.
Delphi 7
Follow Up:
from mghie comments, i rethought about it.
I removed the TPresence Component from the form (which caused some strange IDE errors, that might have had something to do with it) and created it design time, assigning everything that was needed. Now it works, but putting the TPresence Component back on the from brings the error back.
Thankyou for your help guys, i should be able to work this one out now, if i can't ill reopen another question :)
You seem to be thinking that the exception is raised because the client field of Presence1 is not set - if you do however get the exception "Read of address 00000034" it means that the Self pointer in the SetStatus() call is nil. That would indicate that you call SetStatus() on an unassigned TPresence reference. It is not really possible to tell the reason for that from the snippet you posted, but it should get you started debugging.
I would still advise you to write a proper setter method for all component references in your own custom components - first because you have a better hook when debugging such problems (you can set a breakpoint there), and second because you should always call TComponent.FreeNotification() on such linked components to be able to track their destruction and set the internal reference to nil.
We probably need more of your code. It is possible you are not correctly creating an instance of TPresence which would give you the error you are experiencing. Try to give us a simple as possible code snippet that causes your error.

Resources