Showing posts with label delphi. Show all posts
Showing posts with label delphi. Show all posts

Thursday, September 20, 2007

Developing Hybrid Gadgets for Google Desktop

If you are interested in developing gadgets for Google Desktop you may have heard of so-called hybrid gadget. It is a way to enhance your gadget with functionality that cannot be achieved in pure script and GD's API. Namely, you may write the part of the functionality, natively, as an ActiveX object and use it from the script without a need of having the typelib registered, etc.

If you would like to learn about this technique, I encourage you to read my article I have written for Google Developer Knowledge Base which is called Going Beyond Script: Developing Hybrid Gadgets. I hope you will enjoy it and that the article will prove useful. Feel free to leave here comments regarding the article.

Tuesday, August 28, 2007

Ajax not only for Web: Using XmlHTTPRequest in the standalone application.

If the term AJAX is familiar to you, for sure, you know that the heart of this technology is the XMLHttpRequest object. It may be used in, practically, all the modern browsers that support javascript. Although you would instantiate it in Firefox and new versions of Internet Explorer with the instruction:

var d = new XMLHttpRequest();

originally in Internet Explorer it was not a built-in JavaScript object.
In fact, the command to get XMLHttpRequest was:

var d = new ActiveXObject("MSXML2.XMLHTTP");

what reveals the fact that it was realized as an ActiveX object. Indeed, it was implemented in library called Microsoft XML which exposed COM object MSXML2.XMLHTTP. Its type library is present in msxml3.dll file in windows system folder.
So, if it is nothing more than normal ActiveX class, why not to use it in standalone application, for instance written in Delphi, to transfer data between the application and some web server.
In ActiveX-enabled languages that offer dynamic binding (like pascal) it is not more difficult that javascript code embedded in HTML. Here comes an example in Delphi, which fills a memo control with the code of the website http://www.somewhere.com:

procedure TForm1.Button1Click(Sender: TObject);
var
d: OleVariant;
begin
d := CreateOleObject('MSXML2.XMLHttp');
d.open('get', 'http://www.somewhere.com', false, EmptyParam, EmptyParam);
d.send('');
if (d.readyState = 4) and (d.status = 200) then
Memo1.Lines.Text := d.responseText;
end;

Simple, isn't it?
If you prefer static binding (for example, to take advantage of code completion) you may import ActiveX type library Microsoft XML 3.0. Then, your code would look like:

uses msxml2_tlb;

procedure TForm1.Button1Click(Sender: TObject);
var
d: IXMLHTTPRequest;
begin
d := CoXMLHTTP40.Create;
d.open('get', 'http://www.somewhere.com', false, EmptyParam, EmptyParam);
d.send('');
if (d.readyState = 4) and (d.status = 200) then
Memo1.Lines.Text := d.responseText;
end;

You may now be thinking "Wait!, but A in Ajax stands for asynchronous, and here your are blocking program, using XMLHttpRequest synchronously". Yes, we may do it also asynchronously, but one problem arouses here - handling onreadystatechange event. In reality, it is not an event as understood in ActiveX. You may know that, in fact, JScript is incapable of sinking ActiveX events. Thus, Microsoft architects made onreadystatechange to be a property you may assign JScript function to. Therefore, what we have to assign must be, at least, the imitation of JScript routine. As you may have realized, everything in JScript is an object - internally represented by a pointer to IDispatch interface. So are functions. To execute the function you call Invoke with DISPID equal to 0 on its IDispatch.
In Delphi, therefore, JScript's function may be imitated by an object of the class derived from TInterfacedObject and implementing IDispatch interface (providing implementation for Invoke method is enough).

The full example of asynchronous HTTP request follows here:

uses comobj, msxml2_tlb;

type
TAjaxEvenFunc = procedure (d: Variant) of object;
TAjaxEvent = class(TInterfacedObject, IDispatch)
private
d: Variant;
func: TAjaxEvenFunc;
public
constructor Create(const d: Variant; const func: TAjaxEvenFunc);
function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult: Pointer; ExcepInfo: Pointer;
ArgErr: Pointer): HRESULT; stdcall;
function GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount: Integer;
LocaleID: Integer; DispIDs: Pointer): HRESULT; stdcall;
function GetTypeInfo(Index: Integer; LocaleID: Integer;
out TypeInfo): HRESULT; stdcall;
function GetTypeInfoCount(out Count: Integer): HRESULT; stdcall;
destructor Destroy; override;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
d: IXMLHTTPRequest;
begin
d := CreateOleObject('MSXML2.XMLHttp.3.0') as IXMLHTTPRequest;
d.open('get', 'http://www.onet.pl', true, EmptyParam, EmptyParam);
d.onreadystatechange := TAjaxEvent.Create(d, EventHandl) as IDispatch;
d.send('');
d := nil;
end;

procedure TForm1.EventHandl(d: Variant);
begin
if (d.readyState = 4) and (d.status = 200) then
Memo1.Lines.Text := d.responseText;
end;

{ TAjaxEvent }

constructor TAjaxEvent.Create(const d: Variant;
const func: TAjaxEvenFunc);
begin
inherited Create;
self.d := d;
self.func := func;
end;

destructor TAjaxEvent.Destroy;
begin
func := nil;
d := Null;
inherited;
end;

function TAjaxEvent.GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount,
LocaleID: Integer; DispIDs: Pointer): HRESULT;
begin
Result := E_NOTIMPL;
end;

function TAjaxEvent.GetTypeInfo(Index, LocaleID: Integer;
out TypeInfo): HRESULT;
begin
Result := E_NOTIMPL;
end;

function TAjaxEvent.GetTypeInfoCount(out Count: Integer): HRESULT;
begin
Result := E_NOTIMPL;
end;

function TAjaxEvent.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT;
begin
if DispID <> 0 then
begin
Result := E_INVALIDARG;
exit;
end;
if Assigned(func) and not VarIsNull(d) then
func(d);
end;

Wednesday, August 15, 2007

JScript arrays and COM objects, part 2

In the previous post I have been discussing the scenario where we have COM object and the script in JScript and we need to interchange the array of data between them. I have demonstrated how to convert, in your JScript code, the vb-style array received from call to ActiveX object to the array native to JScript. To that, fortunately, the architects of JScript provided us with a tool - VBScript class. However, in reverse situation we don't have any object or routine in JScript scripting engine that would let us or help us converting JScript array to VBArray.

Eric Lippert in his blog states that, although he started writing code to manage conversion to VBArray, it was eventually abandoned and there is no way to do this.
And, actually, this is a truth. JScript engine does not provide us with any way to do that conversion. But why not try looking for it outside the engine but in what is by default available?
Fortunately, here our quest is successful and what we find is that there a COM object in WSH called Scripting.Dictionary. It is, well, as its name says, a dictionary, but what would be most important for you is that it has a method called Items which returns all the items in the dictionary as a VBArray object. So now, I am sure, you know what to do. Here is a code snippet of the function that converts JScript arrays into VBArray:

function GetVBArray(jsArray)
{
var dict =
new
ActiveXObject("Scripting.Dictionary");

for (i in jsArray)
{
dict.add(i, objJSArray[i]);
}

return dict.Items();
}

However, it may have some drawbacks like efficiency. But if it is not critical to your script it will suffice. On the other hand, if you are also an author of the COM object it would be better to just pass JScript array and deal with it in the code, wouldn't it?

If you read my previous post you probably remember that I wrote that in JScript arrays are nothing more than objects. You may also remember that JScript passes objects to automation objects as a pointer to IDispatch interface. Therefore, we may query the IDispatch object about the elements of array, can't we?

Below there is a piece of code in pascal (delphi) of the method that can both accept and process VBArrays and JScript arrays (to be precise, one-dimensional one):

procedure TSomeObject.ProcessArray(SomeArr: OleVariant);
var
i: integer;
ind: array [0..0] of integer;
begin
if VarIsArray(SomeArr) then // (1)
begin
for i := VarArrayLowBound(SomeArr, 1)
to
VarArrayHighBound(SomeArr, 1) do
begin
ind[0] := i;
ProcessElement(VarArrayGet(SomeArr, ind));
end;
end
else if VarIsType(SomeArr, VT_DISPATCH) then // (2)
begin
for i := 0 to SomeArr.length - 1 do
begin
ProcessElement(SomeArr.pop());
end;
end
else
raise EOleException.Create
('Parameter is not an array!',
E_INVALIDARG, '', '', 0);
end;

My example is in Delphi, but if you prefer, for instance, programming in C++ and ATL you can follow the same reasoning. However it will consume more code, since C++ semantics do not allow that you do late binding and you need to do that manually by pairs of calls to IDispatch's GetIDsOfNames and Invoke. In Delphi, we could use its magic of having IDispatch reference in Variant variable and leave it to Delphi to play with name resolving and calls to IDispatch methods.

Now let us analyze the above code. Firstly, in the if in (1) we are checking if the variant contains the traditional VBArray. If so, we process as we normally do with safe arrays. If not, we again examine our variant parameter if its content is IDispatch object. If so, it's probably the JScript array. Therefore, we can try getting the length property or get all elements by calls to pop method. You may also get the value at the given index, but it cannot be done automatically in Delphi. All you need to do is to extract an IDispatch interface, invoke GetIDsOfNames for the given index (which as you know, need not be an integer) and then Invoke retrieved DISPID to get the actual value.

That is all about arrays in JScript and COM object, I wanted to say for now. I hope somebody will find it usable. Maybe, I will also post in the future sample in C++ and ATL, stay tuned ;).

Friday, August 10, 2007

Controlling Winamp programmatically using Delphi

I wanted in one of my project to control Winamp from application written in Delphi. It is well-known that Winamp can be controlled programmatically by finding the Winamp's window. It can be done performing the following Win32 API call:

hwnd_winamp := FindWindow('Winamp v1.x', nil);

Winamp window's class is always Winamp v1.x regardless its actual version. Once you have the handle to winamp's window you can controll it by sending to it certain messages which are specified in Winamp's SDK. However, the SDK on Winamp's website is available only for C++ developers. By googling over the Internet I have come across the translation of those header file to pascal done by Carlos Andres Osorio Gonzalez. However, it is based on the antique version of SDK and is lacking new features. I've decided to extend it, translating the lacking entries from the latest version of C++ SDK.
What I've come up with can be downloaded here or can be viewed here in browser by clicking here.

Enjoy it, but I cannot guarantee that it is free of errors.

There were visits to this blog since 20.08.2007.