Check if Delphi OLE connection still exists - delphi

When I open an Office application e.g. Word, it appears as an application in the Task Manager. If I kill it from there, calling any specific Word function later causes EOleSysError exception. That's normal and works fine. The question is, can Word or any other OLE application existence be checked in a common way without knowing Word it or not?
var App, Obj: Variant
begin
App := CreateOleObject('Word.Application');
Sleep(100);//placing breakpoint here
// killing Word
// checking if App connection still exists
IUnknown(App).QueryInterface(IUnknown, Obj);//no exception, doesn't work
App.Documents.Open('c:\1.docx');//Exception is raised, works but Word specific
end;

Related

Trapping ADO Provider cannot be found error in Delphi

I have an application written in Delphi that uses an iSeries ODBC connection.
There are some workstations where I do not want to install the iSeries software, and on these workstations, I won't be updating any of these databases anyway.
Is there a way I can trap when this error message is generated? At that point, I can just set a variable like NoUpload to true and not allow the connection on the workstation.
It appears to happen before I ever attempt to even open one of the tables - just by having the ConnectionString set when the application starts fires the message.
Thanks in advance!
You can check the existing ADO providers of the system with ADODB.GetProviderNames
Ideally, you should look for an option to check your condition without an exception being raised. So Sir Rufo's answer is a good place to start.
Another option might be to not include the Provider in the ConnectionString, but set it independently via the Provider property at run-time (most likely only after confirming that it's supported).
However, since you mentioned you're getting an exception before you even attempt to open a table, there are a few things to check (assuming you've been setting up your components at design time):
Have any data sets accidentally been left Active at design time?
Has the Connection been left active at design time?
Are there any options in the ConnectionString that could immediately trigger the error?
Failing the above you could provide a hook for application exceptions. (And really more of a last ditch effort.)
Declare a handler method using with the following signature: TExceptionEvent = procedure (Sender: TObject; E: Exception) of object;. And assign it to Application.OnException. E.g.
procedure Handle(ASender: TObject; E: Exception);
begin
if ISeriesNotInstalledError(E) then
begin
FNoUpload := True;
end
else
begin
Application.ShowException(E);
end;
end;
NOTE: There are some important considerations in following this approach. Since you see this as a standard Use Case, you don't want to be bothering your users with messages. This is also much better than a localised exception handler (a common programming error) because if a caller routine triggers this error you don't want the caller to mistakenly run as if nothing went wrong; when quite clearly something did.

Program still in taskmanager after calling Halt

The problem is that as my first executable statements I want to check if I can read from a databse. If I can't, I call MessageDlg to explain so, then I Halt;.
However, after closing the dialog, I still see the application in the tak manager (and if I stop it and re-run the application, the same thing occurs).
Any idea what I am doing wrong?
Global.ADQuery1 is an AnyDac database access component. I access the d/b by IP address. The code works fine when I set my PCs address to the d/b address and gives the reported problem when I change my IP address (hence, can't access the d/b, which throws an exception).
procedure TMainForm.FormCreate(Sender: TObject);
begin
try
Global.ADQuery1.Open('SHOW DATABASES');
except
On E: Exception do
begin
MessageDlg('Database access problem', mtError, [mbOK], 0);
Halt;
end;
end;
[update] when I run in the IDE, after catching
(EMySQLNativeException) : "[AnyDAC][Phys][MySQL] Can't connect to MySQL server on '10.21.18.211' (10060)"
I catch an EIdWinSockStubError either the program has not called wsastartup or wsastartup failed - but I don't udnertsand how it is thrown ... I guess that Application.Terminate calls may main form's FormClose, which doesn't do anything with my Indy components, but I guess that when the parent form is destroyed then its children will be too.
[further update]
My TMainForm.FormCreate now says only
Sleep(1000);
PostMessage(Handle, UM_PROGRAM_START, 0, 0);
And I moved all the code into the stat of function that handles that. Surely everything is created at that time? So, why does my Indy component throw an exception?
Maybe I should put the PostMessage() in my [application].pas after Application.Run(); ?
(Aside: 1) how do others generally handle application start in this way? 2) does anyone have an application skeleton? I was thinking of creating one with options to handle minimize to system tray, only allow one instance, recent files menu, etc, etc) - although that might be better as a separate question
The Halt procedure is not the immediate process-killer we sometimes mistake it for. It calls the unit-finalization sections of all your program's units, so your program might be stuck in one of those, perhaps waiting for something to happen to your form, which isn't going to happen since your OnCreate handler hasn't returned yet.
You could use the debugger to find out what your program is doing or waiting for.
To really get out of a program as fast as possible, skip Halt and go straight to ExitProcess. That's the final thing Halt calls.
Application.Terminate is actually farther from the point where any real termination occurs since it's really just an advisory command; the application won't terminate until it reaches the message loop.
Better yet, find a more graceful way to exit your program. For example, test your database before creating your form so you're not left in the awkward position of having a half-created form that you don't really want anymore.

Does TQuery.Unprepare close the query result in Delphi?

I wonder whether in Delphi calling
Query1.Unprepare;
implicitly closes Query1, if it was previously active. Such that e.g. calling Next on it will fail.
You might say, just go ahead and try but I did on a 64-bit Windows 7 system and had all sort of problems with it until finally my BDE Administrator seems to be completely broken. So I decided to just ask this questions before I start to find out, how I can get BDE running on my system ;-)
You can not use Prepare/Unprepare on an open dataset. you need to close it first.
unit DBTables;
...
procedure TQuery.SetPrepared(Value: Boolean);
begin
if Handle <> nil then DatabaseError(SDataSetOpen, Self);
...
// SDataSetOpen = 'Cannot perform this operation on an open dataset';

Application freezes on call to SetLength

This question might or might not solve my problem - but I hope to learn how Delphi/Windows can behave in a way which can cause this.
I have an application which uses a 3rd party component to load an Outlook .msg file.
In some cases (specific mails) the application freezes when calling SetLength (inside of the component, I have the source code).
This happens sometimes when setLength is called inside of a procedure which loads the properties from the file (stream). It happens the exact same place on the same mail - and can be reproduced every time.
Obviously the component does a lot of stuff and it is probably a sideeffect of some of this. However, the mails contains confidential data which I cannot send to the developer of the 3rd party component, so I cannot send it to him to debug it.
The program is running under windows XP on a domain.
The curious thing is that it only happens when the user running the program is not set to be administrator on the local machine.
ms := TMemoryStream.Create;
try
WriteStorageToStream(SubStorage, ms);
ApplyValue(ms, ms.Size)
finally
ms.Free;
end;
procedure ApplyValue(Stream: TStream; brLen: Integer);
var
s: AnsiString;
begin
SetLength(s, brLen); // this freezes it all. brLen=3512
FillChar(s[1], brLen, #0);
Stream.Read(s[1], brLen);
Value := s;
end;
What WriteStorageToStream does exactly is unknown to me, but since we are not manipulating the stream and brLen has an integer value, I assume it's irrelevant.
I'd say it was simple memory overwrite, causing a failure of the memory manager when the SetLength is called which then tries to use the memory management structures. The problem is in WriteStorageToStream(SubStorage, ms);
To find it, use the FastMM debug version with the memory overwrite detection options turned on.
There's absolutely no reason SetLength would freeze on a AnsiString that's only 3512 characters long. How are you sure that it's freezing there and not somewhere earlier (like in WriteStorageToSteam)? Presumably you're stepping through this in the debugger. Does the CPU spike to 100% on that process thread when it's frozen? The fact that it freezes only on certain emails indicates to me that something in the contents of those emails is causing the freeze. The call to SetLength has nothing to do with the contents; it only cares about the length.

Added the {APPTYPE CONSOLE} directive and now my application runs very slowly. Moving the mouse makes it run faster

I am trying to extend a 3rd party application so that it can be invoked via command line in addition to using the windows form GUI (mixed mode is desired). It's a fairly simple program which basically loads a file and then you click a button it starts sending UDP network packets.
I need to invoke the application from another and would like to pass in an argument and need to be able to return the ExitCode to the calling app. From what i've read, in order to do so you need to add the compiler directive {APPTYPE CONSOLE}.
I did this and my application worked as I wanted it to except sending the network packets slowed down to a crawl. I found that whenever I moved my mouse around on the form. That the network transfer rate increased significantly. I suspect there is some type of Windows Message queue problem and moving mouse is causing interrupts which in turn is causing the message queue to be processed?
I have googled around and tried calling Application.ProcessMessages and PeekMessages in a Timer with a 1ms interval and that didn't help at all. I found in this user manual for some other application it says that Indy 10 is supported in both APPTYPE CONSOLE and GUI types. Quite frankly this just confuses me as I would have assumed that all network library would work in both modes... but like I said I'm not familiar with Delphi.
I am positive that the issue is isolated to a single line in my application and that is whether or not {APPTYPE CONSOLE} is included or not.
Anyone have any ideas?
Version Info:
Delphi 7 Personal (Build 4.453)
Indy 9.0.4
If you add {APPTYPE CONSOLE} to your application even though you desire mixed mode execution, then you will have to live with a console even when the application is in GUI mode. You can of course close the console, but this will cause some flicker and feels a bit hackish to me.
You should be able to do what you want without a console program. A small test program proves that the exit code can be read from a GUI program:
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Close;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ExitCode := 42;
Timer1.Interval := 1000;
Timer1.Enabled := TRUE;
end;
If this is executed with the following cmd file:
#echo off
start /WAIT project1.exe
echo %ERRORLEVEL%
the program shows its main form for 1 second, closes, and the script prints 42 to the console window.
Now for capturing the output - doing this from a GUI program is actually easier than doing it from a console program, if you allow for the use of a temporary file. You need to start the program with a command line parameter anyway, so why not give it the name of a temporary file, wait for the application to finish, read in the file and delete it afterwards?
If you want an application to return an "error" code there is no need to make it a console application. You only need to set the ExitCode, e.g.
ExitCode := 10;
in a batch file
#Echo off
project1
echo %errorlevel%
Will display the application, then display 10 when.
Note: It is also possible to create a console window dynamically from the windows API using AllocConsole or to attach using AttachConsole.
I created an object wrapper for this once, but no longer have the code available. From memory it didn't support redirection (because I didn't need it).
If I understand you correctly, then you want your app to have two modes:
If no argument is passed, run in GUI mode
Run in non-GUI mode otherwise
The easiest is if you can centralize your logic so it can be called from one method (CoreLogic in my example).
The below app then should work fine.
Two tricks:
Application.ShowMainForm := False; that will not make the MainForm show at all.
ExitCode := 327; which will set your return code (like mghie and Gerry already mentioned).
A few notes:
because the CoreLogic does not process any windows messages, anything in your application that depends on Windows messages being processed will stall.
if you need windows message processing, then just all Application.ProcessMessages() inside your CoreLogic
if you need your form to be visible, then you change the logic inside your MainForm to test for the commandline parameters, and exit when it's work as been done (by calling Application.Terminate()). The best place to put that logic in is the event method for the MainForm.OnShow event.
Hope this helps :-)
program VCLAppThatDoesNotShowMainForm;
uses
Forms,
MainFormUnit in 'MainFormUnit.pas' {MainForm},
Windows;
{$R *.res}
procedure CoreLogic;
begin
Sleep(1000);
ExitCode := 327;
end;
procedure TestParams;
begin
if ParamCount > 0 then
begin
MessageBox(0, CmdLine, PChar(Application.Title), MB_ICONINFORMATION or MB_OK);
CoreLogic();
Application.ShowMainForm := False;
end;
end;
begin
Application.Initialize();
Application.MainFormOnTaskbar := True;
TestParams();
Application.CreateForm(TMainForm, MainForm);
Application.Run();
end.
A timer with 1ms will only fire about every 40 ms (due to Windows limitations), so it won't help. I have seen effects like you describe with mixed console and GUI apps, another is that they don't minimize properly.
Instead of enabling the console in the project, you could probably use the CreateConsole API call (Not sure whether the name is correct) to create one after the programm was started. I have seen no adverse effects in the one (!) program I have done this.
But this is only necessary if you want to write to the console. If you only want to process command line parameters and return an exit code, you do not need a console. Just evaluate the ParamCount/ParamStr functions for the parameters and set ExitCode for the return value.
If some threads in your console application call Synchronize (and I guess the Indy stuff is actually doing that), you have to make some preparations:
Assign a method to the WakeMainThread variable. This method must have the signature of TNotifyEvent.
Inside this method call CheckSynchronize.
For additional information see the Delphi help for these two items.

Resources