Converting a Delphi application to run as a service - is it necessary? - delphi

I have a delphi app that logs data from various places and writes the data to a file. The app has quite an extensive GUI to allow display of the data, configuration of the options, etc.
One user has requested that the app be changed to that it can be run as a service. His reasoning is that the app could then be started at boot time and run without any user being logged in and would be available regardless of who was logged in.
My question is this: Is there any other solution that would enable me to install the app as it now exists so that it would still run with no user logged in and still be available to all users?
My gut feeling is that converting the app to run as a service is not trivial. I assume you would need 2 apps - the "headless" service application, and a GUI that was run by users on demand that could interact with the service (comments welcome here also).

I usually create my application in such a way that it can be started as a service or as a GUI, via a commandline switch /GUI.
When the application runs with a GUI, I instantiate and start the service class "manually".
Advantages:
It'll run the same code, making it very easy to debug the service. You can just put breakpoints and step through your code without having to "attach" to a running application.
Because of the GUI, you can see what your service would be doing, and interact with it, via listviews and buttons, even on remote servers where you don't have a debugger. Having to interact with your service via logs and configurations is crappy and slow.
Example dpr, from a project that works like this:
program xxxx;
uses
SysUtils,
SvcMgr,
.......;
{$R *.res}
begin
GlobalAppId := 1;
MapMatcherController := TMapMatcherController.Create(nil);
try
if FindCmdLineSwitch('GUI',['/','-'],True) then
begin
Forms.Application.Initialize;
Forms.Application.MainFormOnTaskbar := True;
Forms.Application.CreateForm(TfrmMain, frmMain);
Forms.Application.Run;
end
else
begin
SvcMgr.Application.Initialize;
SvcMgr.Application.CreateForm(TsrvMapMatcher2, srvMapMatcher2);
SvcMgr.Application.Run;
end;
finally
MapMatcherController.Free;
end;
end.
Oh, another thing to keep in mind is that services usually run as a "system" user, which means you'll have different privileges and settings (for example drive letter mappings).

There are commercial (and free) solutions like Firedaemon, which will run (almost) any application as a service.
On a sidenote, it shouldn't really be hard to separate logic and user interface - you should've done that already when you developed the application. Just because Delphi makes it easy to write business logic in the code behind associated with the user interface, that doesn't mean you should really do it. Have a look at the presentation pattern's at Martin Fowler's site.

In general is possible to have a mixed single exe which in turn runs as a service or runs as a full GUI standard application.
How much effort your application needs to fit this category is matter of how is it designed, specially in the kind of coupling it have between business logic and user interface logic.
One great example of this kind of application comes with Delphi itself: scktsrvr.exe in your $DELPHI\bin directory runs as a GUI application or as a service (run scktsrvr.exe /install to auto-register the service and use management console to start/stop it.
in folder $DELPHI\source\db you will find the project files (scktsrvr.dpr/res, ScktCnst.pas, ScktMain.pas/dfm). Take your time to inspect how is it done and, who knows... maybe this is what you're looking for your application.
Take in account since Windows Vista interactive services are not allowed to interact with the user at his/her desktop. An administrator have to enable the interactive services detection and the user have to change to session 0 desktop in order to interact with your service (by interact it means to see and interact with your service forms)

You can try to use svrany, a tools to run an application as service.
It's parts of Server Resource Kit Tools.
try this link for 2003 server resource kit download.

It depends a little on your application, but generally it is achievable. Try this: http://iain.cx/src/nssm. Don't forget to start all services that you application depends on BEFORE you start your application as a service. Google around for info on how to do that.

You could write a simple service that starts your application. But if you care about your app future, I would go the service way. Yes, you would have to split the application in two pieces, the client/GUI part and the service itself, especially since Vista and 7 made much more difficult for a service to display a user interface for security reasons.
Services have several advantages, they run in their separate session, they can be set to run with a given user that could be different from the logged-on one, only user with proper privileges can control them, Windows can automatically restart them (or perfom other actions) when they fail.

Related

JclAppInstances between service and desktop

I'm using the following code in an application that automatically detects when it is run whether it is running as a service or desktop application and behaves appropriately for the situation.
JclAppInst.JclAppInstances('<application descriptive label>').CheckSingleInstance;
The code is embedded into an initialization block at the bottom of a unit that contains code responsibility for acknowledging the service status and displaying key desktop information so I know this unit is included in both modes of operation. The CheckSingleInstance call works perfectly in desktop mode making sure that only one instance is run but doesn't seem to be able to detect if the application is currently running as a service.
Unfortunately I can't work out why the JclAppInstances would be affected by the difference. Both instances are running from the same folder but are operating as different users (ie service user differs from desktop user) but my understanding is different users should work.
Does anyone know whether it is possible to do this with the JclAppInstances and if so what my problem is?
It seems quite clear that the JclAppInstances class doesn't support the required functionality and any solution based on using this Jedi component should refer to the following StackOverflow answer instead.
one instance of app per Computer, how?

Exposing the same Auto of Process COM server from multiple copies of the same executable

I have a media application (written in Delphi 2010 but I am not sure that's entirely relevant) and it only allows one instance (via mutex).
One of my customers would like to run 2 instances of the app by duplicating its install and all of its application data as this will allow him to run the output to two different sound cards, giving him two audio zones.
Now I can allow the second instance via command line switch, thus creating a differently named mutex and even allowing him to send controls to either instance of the appliction via command line switches or windows message passing.
My application also exposes a COM interface for automation purposes, obviously this provides a much richer interface than command line and makes it much easier to get information out of the application.
So my problem is that, as far as I am aware, I can only expose the COM interface to one executable. Now I know that makes sense, but I am wondering if anyone can think of a workaround to this.
I had a quick try at duplicating the registry keys for my HKLM\Software\Classes\AppID thus making AppIDv2 and got as far as it lanching the other copy of my app, but I guess it all came unstuck when it hit the more specific GUIDS for the TypeLib etc. Mind you, I know I overstepped the bounds of my knowledge!
My thought is that if I can create a different AppID string and ultimately target the exe sitting in different locations then we'd at least be able to do some automation via scripting COM Automation but I suspect that the requirement for GUIDs is ultimately going to let me down.
Another option may be to move my COM to inprocess and then have multiple compiled versions of my application that expose an instance of the main interface via new AppIDs, but that gets messy when you want the DLL to know all about the running instance of your application.
Any ideas welcome. Thanks in advance.
It sounds like you want to register yourself in the Running Objects Table (ROT).
i'm likening your problem to that of multiple copies of Excel running. COM has a mechanism to allow someone to find my the running instances of Excel and connect to one of them.
Out of process COM objects are expected to register themselves with the ROT. Callers can then use GetActiveObject to find your instance:
To automate an Office application that is already running, you can use the GetActiveObject() API function to obtain the IDispatch pointer for the running instance. Once you have this IDispatch pointer for the running instance, you can use the methods and the properties of the running instance.
You might not like it, but i believe the solution is that there is one application interface, and that "first" application acts as the gateway to other "instances" of your application (i.e. your automation server).
i'm not an expert in out-of-process COM automation, but i think i've read enough to believe that's the (unfortunate) answer.
See also
Registering the Active Object with API Functions
How To Attach to a Running Instance of an Office Application
You do indeed need the Running Object Table (IRunningObjectTable). Ian's answer is largely correct.
http://msdn.microsoft.com/en-us/library/ms695276(v=VS.85).aspx
However, it is possible to have two distinguishable instances in the ROT, allowing both copies of your app to be accessed because their monikers are distinguished.
Martyn

Emulate terminal services

I am a seasoned Delphi developer and would like to create something like seamless terminal services where an application is executed on a server but appears on the the desktop of the client.
To someone working on the server I don't want them to see the remote application running (except if they looked in at the list of running processes).
I'm lost as to how to go about this, where to start, how to get an application to render to a surface other than the servers desktop.
Starting from 2008 Terminal Services (which has been rebranded to Remote Desktop Services) offers RemoteApps which do exactly what you describe. Citrix (XenApp) can do this on all windows (server) versions. So you might want to look at those products before deciding to recreate them yourself.
If you do decide to go on, this link might be interesting, it's a sample project called "Extending Microsoft's Terminal Services Client To Provide Seamless Windows"
From what you are describing, I'd say you should be looking at writing a windows service (not terminal services) and using a inter-process-communications (IPC) system to get status information to a "client" application that can be run by the appropriate user, either on the same machine or another over the network.
Myself, I do exactly this using the RemObjects SDK which makes my client application look like it is just making function calls, but actually they go to the server which implements them. The server can then get on with its job in one (or more) thread, and all the user interface is done in the client which finds out what to display using the IPC channel.

Does anyone know about issues between Citrix and Delphi 2007 applications? (And perhaps other development languages?)

The situation is simple. I've created a complex Delphi application which uses several different techniques. The main application is a WIN32 module but a few parts are developed as .NET assemblies. It also communicates with a web service or retrieves data from a specific website. It keeps most of it's user-data inside an MS Access database with some additional settings inside the Registry. In-memory, all data is converted inside an XML document, which is occasionally saved to disk as backup in case the system crashes. (Thus allowing the user to recover his data.) There's also some data in XML files for read-only purposes. The application also executes other applications and wants for those to finish. All in al, it's a pretty complex application.
We don't support Citrix with this application, although a few users do use this application on a Citrix server. (Basically, it allows those users to be more mobile.) But even though we keep telling them that we don't support Citrix, those customers are trying to push us to help them with some occasional problems that they tend to have.
The main problem seems to be an occasional random exception that seems to pop up on Citrix systems. Never at the same location and often it looks related to some memory problems. We've p[lenty of error reports already and there are just too many different errors. So I know solving all those will be complex.
So I would like to go a bit more generic and just want to know about the possible issues a Delphi (2007) can have when it's run on a Citrix system. Especially when this application is not designed to be Citrix-aware in any way. We don't want to support Citrix officially but it would be nice if we can help those customers. Not that they're going to pay us more, but still...
So does anyone know some common issues a Delphi application can have on a Citrix system?
Does anyone know about common issues with Citrix in general?
Is there some Silver Bullet or Golden Hammer solution somewhere for Citrix problems?
Btw. My knowledge about Citrix is limited to this Wikipedia entry and this website... And a bit I've Googled...
There were some issues in the past with Published Delphi Applications on Citrix having no icon in the taskbar. I think this was resolved by the MainFormOnTaskbar (available in D2007 and higher). Apart from that there's not much difference between Terminal Server and Citrix (from the Application's perspective), the most important things you need to account for are:
Users are NEVER administrator on a Terminal or Citrix Server, so they no rights in the Local Machine part of the registry, the C drive, Program Folder and so on.
It must be possible for multiple users on the same system to start your application concurrently.
Certain folders such as the Windows folder are redirected to prevent possible application issues, this is also means that API's like GetWindowsFolder do not return the real windows folder but the redirected one. Note that this behaviour can be disabled by setting a particular flag in the PE header (see delphi-and-terminal-server-aware).
Sometimes multiple servers are used in a farm which means your application can run on any of these servers, the user is redirected to the least busy server at login (load balancing). Thefore do not use any local database to store things.
If you use an external database or middleware or application server note that multiple users will connect with the same computername and ip address (certain Citrix versions can use Virtual IP addresses to address this).
Many of our customers use our Delphi applications on Citrix. Generally speaking, it works fine. We had printing problems with older versions of Delphi, but this was fixed in a more recent version of Delphi (certainly more recent than Delphi 2007). However, because you are now running under terminal services, there are certain things which will not work, with or without Citrix. For example, you cannot make a local connection to older versions of InterBase, which use a named pipe without the GLOBAL modifier. Using DoubleBuffered would also be a really bad idea. And so on. My suggestion is to look for advice concerning Win32 apps and Terminal Services, rather than looking for advice on Delphi and Citrix in particular. The one issue which is particular to Citrix that I'm aware of is that you can't count on having a C drive available. Hopefully you haven't hard-coded any drive letters into your code, but if you have you can get in trouble.
Generally speaking, your application needs to be compatible with MS Terminal Services in order to work with XenApp. My understanding is that .NET applications are Terminal Services-compatible, and so by extension should also work in a Citrix environment. Obviously, as you're suffering some problems, it's not quite that simple, however.
There's a testing and verification kit available from http://community.citrix.com/citrixready that you may find helpful. I would imagine the Test Kit and Virtual Lab tools will be of most use to you. The kit is free to use, but requires sign-up.
Security can be an issue. If sensitive folders are not "sandboxed" (See Remko's discussion about redirection), the user can break out of your app and run things that they shouldn't. You should probe your app to see what happens when they "shell out" of your app. Common attack points are CHM Help, any content that uses IE to display HTML, and File Open/Save dialogs.
ex: If you show .chm help, the user can right-click within a help topic, View Source. That typically opens Notepad. From there, they can navigate the directory structure. If they are not properly contained, they may be able to do some mischief.
ex: If they normally don't have a way to run Internet Explorer, and your app has a clickable URL in the about box or a "visit our web site" in the Help menu, voila! they have access to the web browser. If unrestrained, they can open a command shell by navigating to the windows directory.

Why do forms fail in Windows Services

I understand that Window's Services have no desktop, and can't access any of the user's desktops directly (indeed, they can run when there is no desktop loaded). Why is it though that launching a form in a Window's Service causes an error?
A service should run without any user interaction, so there is no need for a form. If a service has to wait around for user feedback then it probably isn't going to be doing what it is supposed to.
You have to understand three related concepts: sessions, windows stations and desktops. But because there's a one-to-one relationships between sessions and stations, we can broadly ignore stations for this discussion. A session contains a station (winSta0 being the only interactive station) and stations contain one or more desktops.
Now session architecture differs according to Windows version. For NT <= 5 (XP/2003 and everything before them) services execute in session 0 along with the interactive user's apps. This is why you can configure services to interact with the desktop in these Windows NT versions - they are in the same session. For NT >= 6 (Vista, Server 2008 going forwards), services exists in session 0 but the interactive desktop is in another session. This is what's known as "service hardening", and is basically a security fix.
So since session 0 apps cannot get at the interactive console, it makes no sense for them to attempt to display a user interface of any kind.
Just to make this more confusing, Vista has a temporary kludge to cater for this situation: if an app in session 0 tries to create a dialog, Windows will trap this and present a warning to the user so they switch to a (I presume temporary) desktop where they can interact with the dialog. However this measure is explicitly temporary and you cannot rely upon it being in future Windows releases. I've seen this working in native code, but I suspect you are in managed code and the runtime is being smart enough to catch your behaviour and deliver a metaphorical slap to the hindquarters :-).
Ummm... what and whose desktop is that form going to appear on, exactly? A 'desktop' is an operating system concept: each window handle is owned by a specific desktop within a window station belonging to a single (interactive) user. The process within which the service is executing isn't going to find the user's visible desktop in its window station. For a rather dry reference, look at MSDN.
Actually, it's even nastier. You might be able to configure permissions for the service to be able to create a desktop -- but then nobody will see it! Alternatively, you could grant the process the rights to switch desktops, and confuse the heck out of the user!
There's a setting you must enable in order to allow your Windows Service to access certain folders directly (like desktop) or show forms (including MessageBox pop-ups): "Allow service to interact with desktop"
To see this, right click on My Computer => Manage => Services and Applications => Services. Double-click on a service to access its properties. On the "Log On" tab there is a checkbox for this setting.
Here is an article for how to set it programmatically in C#
[Edit] As Stephen Martin points out in the comments: this is only valid advice for pre-Vista versions of Windows.
Because if nobody is going to see the Form, nobody is going to dismiss it - running a modal dialog is a recipe for a hang - so you want it to complain loudly when this happens rather than sit there quietly until you kill the process (or look at a stack trace to determine what'd going on). (The other obvious problem is, who is going to pick the DialogResult if there is more than one possibility?) You want to know when this is happening. (Assert dialogs that dont throw if they cant show anything are a fun way of making people mad.).
In other words, because you want to know when things are confused enough in your code that a dialog is being shown within a service context.
(I'm assuming you're using Windows Forms on .NET, eve though you didnt tag it as such)
(If you have correctly configured things such that the service is allowed to interact with the desktop, you won't get an Exception)
When a Windows Service is started it is assigned to a Window Station and Desktop according to well documented, though somewhat obscure rules. As mentioned elsewhere it is not assigned to the interactive desktop (unless it is set to interact with the desktop on a pre-Vista OS) but it definitely runs in a desktop.
It is a common misconception that services cannot use UI elements. In fact many services (such as SQL Server) have in the past used hidden windows and windows messages for thread synchronization and work distribution purposes. There is no reason that a Form cannot be shown in a service. If you are getting an error it is due to something you are doing with the form or some component that is on the form. The most likely issues have to do with whether or not you need an STA thread for your form or are you creating a message pump for your form or something similar.
While you certainly can use a form in a Windows Service you almost certainly shouldn't. There will be threading issues, cross apartment call issues, possible blocking UI issues, etc. There are a very few situations where using a window in a service is a good choice but there is a better way, with no UI, in 99.99% of all cases.
Because at the time when the operating system needs to paint the window there is nothing to draw the form on.

Resources