Vote for this Product at ClarionShop
 
Buy now at ClarionShop
Version

www.capesoft.com
Updated 01 October 2007  
c3pa approved
     

Contents

Introduction
Installation
JumpStart - start here - (recommended reading)
Examples
Ground Rules (recommended reading) [updated for Windows Vista]
Global Extension Options  (recommended reading)
Control Templates - the easiest way to add Service buttons to your app (recommended reading)
Object Properties
Object Methods
FAQ
Support
Purchasing SelfService
Distribution

License & Copyright & Credits
Version History


Introduction
 
What is SelfService?
CapeSoft SelfService allows your Clarion 6 applications to be run as Services in Windows NT4, Windows 2000, Windows XP, Windows Server 2003, Windows Vista and better.
 
What do Services offer you?
One of the great features of Services is that they don't require a user to be logged in, in order to run. Services can automatically start on boot up.
 
Services also do not shut down when a user logs off or switches user, so your application is always running.
 
What sort of applications are suitable for being run as a Service?
Any of your applications that behave like a server are ideal candidates for being run as a Service. This would include a whole host of possibilities with NetTalk applications, or any application that you would like to be "always running". Examples would include:
Web servers,
web, ftp or email polling applications,
control applications like air conditioning servers,
server components in client/server applications.
 
How easy is it to make my application run as a Service?
With SelfService you are able to convert your existing applications into services in just a couple of minutes. No hand coding is necessary if you simply want your application to run and install as a service. To maximize the functionality that services offer you we have outlined a list of considerations and tips. These serve as guidelines to help you design and deploy effective and powerful services. To utilize more advanced service functionality a small amount of hand coding may be necessary, which is all clearly documented and demonstrated in the examples.
 
     



Installation

To download the latest installation please visit www.capesoft.com/selfserviced.htm

Please note: SelfService is only available for Clarion 6
(It is not available for Clarion 5 and Clarion 5.5 as the threading model in these Clarion versions does not support multi-threaded services).

Upgrades are free. This may not always be the case, but upgrades have been free for our accessories for the past 10 years.

 


(recommended reading)

Using CapeSoft SelfService in your program used to be really easy (in the days before Vista) - but with the arrival of Vista your service applications do not display any user interaction. This means that you need to split your application into 2 apps - one that contains the user interface, and one that contains the processing part that is the Service functionality, and then create a communication channel between the two applications.

Code Example:
Work through the examples in your Clarion/3rdParty/Examples/SelfService/JumpStart folder. Typically the ClientApp and the VistaService app are the two that typify a very simple Client\Server scenario. We'll use these in the tutorial below.

What you need to do:

The biggest issue in moving your application to a service is separating the GUI from the processing part. In Vista, Services are no longer able to provide a user interface, which means that all user interfacing must be moved to a separate application. Your Vista Service application can still contain windows, they will simply not be displayed. Your interface application can be installed in the Startup programs when the user logs on.

Step 1 - identify the processing elements of your application which will be retained in the Server.

Step 2 - move the GUI (and user interaction) to a separate application.

Step 3 - create a communication channel between your Client app and the Server. Typically this would be with NetTalk.

Step 4 - add the SelfService template to your Server application.

JumpStart Tutorial:

What we are doing:
We are going to create a simple application set (a client which contains the user interface and a server that is the Service). The Service can run as a normal EXE - but in Service mode it will be controlled by the ClientApp. This appset will use NetTalk as the communication channel between the Client and the server apps. Here's a screenshot of what the Client application could look like:

First we'll create the Server application (the Service)

1) Open Clarion 6, and either Open an existing application or Create a New Application for our server (In the Application Properties window make sure the Application Wizard checkbox is off. Press OK.).

2) Go to the Application menu - Global Properties. This opens the Global Properties window. Click on Extensions.

Insert the "Activate_SelfService" template.

Change the Service Name to 'CapeSoftJumpStart' (don't use spaces)
    and the Service Display Name to 'CapeSoft SelfService Jump Start'
    and the Service Description to 'CapeSoft SelfService Jump Start'

While we're in the Global Extensions, add the NetTalk global extension as well. This will be used for our communication channel between client and server, although you could use an alternative communication channel as well (like DDE).

    Press OK, and OK again.

3) Double click on the "Main (ToDo)" procedure and create a Window similar to the following (if you are creating a new application for the server):

4) Add the IncludeNetTalkObject to the Main window (if you're using NetTalk for your communication channel between client and server) and set the Object name to something like ThisSimpleServer. Set the Base Class to NetSimple and on the Settings tab, select the Server option.

Add the following to your data embed:

! We make a group to receive and send data
! This group structure must match exactly at the client so that communication
! will be possible between the server and the client.

ourData     group
command      long
time         long
date         long
AmService    byte
Automatic    byte
ServiceName  string(254)
           
end

ourString string(size(ourData)),over(ourData)

!Equates for the command in the data. These equates must match at the client
          
itemize,pre(equ)
InstallService         equate(100)
InstallAndStartService equate
RemoveService          equate
RequestStatus          equate
          
end

In the ThisWindow.init method, you need to do the following (after the window is opened):

setcursor (CURSOR:Wait)
ThisSimpleServer.Open('
localhost',2251)
setcursor

In the ThisSimpleServer.Process method, add the following code to handle the communication received from the child:

case self.Packet.PacketType
of NET:SimpleAsyncOpenSuccessful
of NET:SimpleIdleConnection
of NET:SimplePartialDataPacket
orof NET:SimpleWholeDataPacket
    ourString = self.packet.bindata[1 :
size(ourString)]
   
display()
    ourData.ServiceName = ''
   
case ourdata.command
   
of equ:InstallService
        gSelfService.InstallService(0)
! 0 = non-silent mode
        ourData.ServiceName = 'Reboot Required: '   !Additional text sent to the client
   
of equ:InstallAndStartService
        gSelfService.InstallAndStartService()
! silent mode
        ourData.ServiceName = '
Reboot Required: '   !Additional text sent to the client
   
of equ:RemoveService
        gSelfService.RemoveService(0)
! 0 = non-silent mode
        ourData.ServiceName = '
Reboot Required: '   !Additional text sent to the client
   
of equ:RequestStatus
        
!No reboot required in Vista, because the Service status has not changed.
    end
    ourData.time =
clock() ! prime our data in the ourString
    ourData.date =
today() ! which is "over" ourData
    ourData.AmService = gSelfService.AmService
    ourData.Automatic = gSelfService.Automatic
    ourData.ServiceName =
clip(ourData.ServiceName) & ' ' & gSelfService.ServiceName
    self.packet.ToIP = self.packet.FromIP
    ! self.packet.SockID is same as sender
    ! self.packet.Socket is same as sender
    self.packet.bindata = ourString
    self.packet.bindatalen =
size(ourString)
    self.send()
end

5) Click on the green tick to close the Window Editor, this will take you back to the Application Tree. Compile and Run the application.

Now we create the client application to contain the user interface

1) Open Clarion 6, and either Open an existing application or Create a New Application for the client(In the Application Properties window make sure the Application Wizard checkbox is off. Press OK.).

2) Go to the Application menu - Global Properties. This opens the Global Properties window. Click on Extensions.

Insert the  NetTalk global extension.

    Press OK, and OK again.

3) Double click on the "Main (ToDo)" procedure and create a Window similar to the following (if you are creating a new application for the server) - use the data in defined in step 4 below for the controls:

4) Add the IncludeNetTalkObject to the Main window (if you're using NetTalk for your communication channel between client and server) and set the Object name to something like ThisSimpleServer. Set the Base Class to NetSimple and on the Settings tab, select the Server option.

Add the following to your data embed:

ourString  string(size(ourData)),over(ourData)

           itemize,pre(equ)   !Equates must be the same in the client and the server
InstallService           equate(100)
InstallAndStartService   equate
RemoveService            equate
RequestStatus            equate
           end

Add the following to your local data

ourData       GROUP,PRE() ! This group must match the Server group
command         LONG 
time            LONG 
date            LONG 
AmService       BYTE 
Automatic       BYTE 
ServiceName     STRING(254) 
              END 
Port          LONG(2251) 

Add the following to your Procedure routines:

SendData Routine
  if ThisSimpleClient.openflag = 0
    ThisSimpleClient.open('localhost',Port)
    exit
  end
  setcursor (CURSOR:Wait)
  clear (ThisSimpleClient.Packet)

  ThisSimpleClient.Packet.BinData = ourString
  ThisSimpleClient.Packet.BinDataLen = size(ourString)

  ThisSimpleClient.Send()
  ourdata.Command = 0
  if ThisSimpleClient.Error = ERROR:ClientNotConnected
    Message ('Sorry the connection has already closed.')
  end
  setcursor

Now add the following to the ThisWindow.init method:

!Open the port first, so we can make sure that the service is running, and run it if it's not
setcursor (CURSOR:Wait)
ThisSimpleClient.DontErrorTrapInSendIfConnectionClosed = 1 ! We want to trap for this error ourselves. The error if it occurs is ERROR:ClientNotConnected
ThisSimpleClient.AsyncOpenUse = 0
ThisSimpleClient.InActiveTimeout = 9000
ThisSimpleClient.Open('localhost',Port)
setcursor
In each of the buttons place the following code:
  !Install and start the service
ourdata.Command = equ:InstallAndStartService
do SendData
  !Install the service
ourdata.Command = equ:InstallService
do SendData
  !Remove the service
ourdata.Command = equ:RemoveService
do SendData
  !Request the service details
ourdata.Command = equ:RequestStatus
do SendData

In the ThisSimpleClient.ErrorTrap method, place the following code:

if self.error = 10061   !Connection refused
 !This means that the server is not running, so let's offer the ability to start it
  case Message ('Open communication channel Failed.|' & |
                'This probably means that the server is not running.|' & |
                'Error = ' & self.Error & '|' & |
                'Would you like to start your Service exe now?',|
                'NetTalk Error',icon:exclamation,button:yes+button:no,button:yes)
  of button:yes
    run('.\VistaService.exe')
  of button:no
    !Don't do anything
  end
end

In the ThisSimpleClient.Process method, place the following code after the parent call:

case self.Packet.PacketType
of NET:SimpleAsyncOpenSuccessful
  if ourdata.Command
      !We were waiting to send a command, but the channel needed to be opened
    do SendData
  end
of NET:SimpleIdleConnection
  self.abort()
of NET:SimplePartialDataPacket
orof NET:SimpleWholeDataPacket
      !We got a reply from the server, let's display the status on the screen
  if self.Error = 0
    if self.Packet.BinDataLen > 0
      ourString = self.packet.bindata[1 : size(ourString)]
      display()
    end
  end
end

5) Click on the green tick to close the Window Editor, this will take you back to the Application Tree. Compile and Run the application.

When the application launches, you can now click on the "Install" button. Run the "Windows Service Manager" (Windows Run: services.msc). You'll see a screen like the following appear.

You can now right click on the CapeSoft SelfService Jump Start entry (see above) and click Start.

Alternatively you can reboot the machine and watch your application start. (Note: You'll need to login before you see the window, but the application was started on boot up, not login.)

Important: Okay, now that that's working this is a great time to read the Ground Rules, and then we will return to completing your JumpStart application.

Part 2

What we are doing:
In Part 1, we add the Service mechanism to an application, now we are going to add some WinEvent functionality, that will allow our application to shut down with out the dreaded "Application still active. Quit the application before quitting Windows" message. (Please make sure you've read the Ground Rules section of the documentation.) This part of the Jump Start should take you less than 10 minutes, to complete.

1) (do this in the server and client applications) Click on the Application menu (in Clarion 6) - Global Properties, and then click on the Extensions button in the "Global Properties" window. Insert the "Enable WinEvent" global extension. (If you can't find WinEvent in the list, then you haven't installed or acquired WinEvent - You'll need to do this first).

On the WinEvent template tick on the "Auto-Shutdown on" checkbox. (You can leave all the rest of the options on their default settings). (This option will prevent Windows from displaying the "Application still active. Quit the application before quitting Windows" message when Windows shuts down.

2) (this is recommended for your client application) Open your client app in the Clarion IDE. Right-click on your Main procedure and choose Extensions from the right-click menu. Insert the WinEvent "TaskbarIcon - WinEvent: Add Icon to system tray" extension:

In the "Name of Icon to add" field enter the following (including the quotes): 'icon.ico'
In the "Icon Tip" field enter the following: 'CapeSoft SelfSevice JumpStart'
Click on the ... button to the right of the IconHandle(long) field.
Add a new long to the LOCAL DATA Main called something like TaskBarIcon
Choose the following options:
   -  Add Show|Hide|Close Menu to Right-Click Popup
   -  Not on Toolbar when Minimized
   -  Disable Titlebar Close
   -  Left-Click Icon Shows Window

7) Return to the Embedded Source window and Insert the following embed code after the "Local Objects - ABC Objects - Window Manager - Init - Open the window" section:

  window{prop:text} = 'SelfService JumpStart started at ' & |
                      clip(left(format(clock(),@T4)))

    (This will show you the time the service was started in the Title bar)

8) Now go back to the Window Editor of the Main window.

Add an "Exit" button or Menu item with the following code embedded into the Accepted code section:
post (event:closedown) ! Will close down the application

Add a Timer to the Window.
Right-click on the Window Title Bar | Properties. Then in the Extra Tab, add a timer value. (100 should be fine).
(You'll need a timer for the Icon to be refreshed correctly when/if your Service becomes visible on the Desktop)

9) Compile and run the application. You can also test starting (and stopping the application) from the Service Manager. You should now see your application running in the task tray as the red dot icon.

    

Examples

There are SelfService examples in your \Clarion\3rdParty\Examples\SelfService\ directory.

Ground Rules (recommended reading)

This section explains some of the concepts that you'll need to consider in order to effectively use Services. Note that Windows Vista changes a number of things about the manner in which services work, and what is allowed, along with how logins work. This is covered in the notes below.

1) Your service runs in a user account of your choice. In the SelfService global extension you can specify which user your service must run in. It's important to choose the correct user as it will affect the behaviour and functionality of your service. SelfService offers you two options:
 
  a)
 
Local System - This is the default user and allows your service to be Interactive (i.e. in Windows versions prior to Vista the GUI will appear to the first user who logs in), but it will not allow network access to other machines shared folders (unless they are accessible to Guest via a null session). This user also cannot open HKEY_CURRENT_USER. NOTE: In Vista, no GUI will be available to the user from the Service. You will need to create a controlling application to provide the interface and allow the user to interact with your Service.
 
  b) Custom - This allows you to specify a user and password. Your service will then run with the privileges of that user. If you give that user account access to shared network folders, then your service can access these folders. This account type does not allow interactive (i.e. Visible) services.

Note: the user account you choose must have a password (it won't work without one).
Note: The user account may need to be preceded by a .\ for example: .\administrator
Note: You'll need to give your account "log in as service rights". (See also Microsoft Information). Which can be done two ways:

a) If you type the account details in to the Windows XP/2003/Vista Service Manager, the Service manager automatically adds "Log in as a Service" rights.
b) You can the Group Policy Editor (gpedit.msc). Local Computer Policy | Computer Configuration | Windows Settings | Security Settings | Local Policies | User Rights Assignments | Log on as a service.

There are also two other built in account types that you can use (you can enter them in the custom fields), but these do not work with NetTalk, and are therefore not recommended:
  i)
 
Network Service (enter NT Authority\NetworkService as the username, no password) - Shared Network folder access, no interactive and not compatible with NetTalk.
  ii) Local Service (enter NT Authority\LocalService as the username, no password) - Limited access user (no networking), no interactive and not compatible with NetTalk

It's important to choose the correct account type, depending on whether you want an interactive service, or a service that has access to network files. Another thing to bear in mind is that if you are using Proxy client software (e.g. Microsoft Proxy) to access the Internet, this may not be available to the Local System account.

2) Your Service needs to be able to shutdown smoothly without displaying the "Application still active. Quit the application before quitting Windows" message. So you're going to need WinEvent to make sure your program automatically shuts down.

3) Including a user interface in a service is NOT recommended, and is not supported at all by Windows Vista and later versions of Windows. You should separate the user interface from the service and run it as a separate application which can communicate with your service and allow the user to manage it. You can do this using NetTalk, DDE etc. Note: You may still have a user interface in the Service application, it will simply not be displayed in Windows Vista - if it is running as a service.

4) A Service can only have one instance started by the Service Manager. Although you can run multiple instances of the same executable by double clicking it, the Service Manager will only open one instance. i.e. If the Service Manager has already started your Service, it won't and can't start another instance.

5) Windows XP/Vista Fast User switching allows users to switch from one user's desktop to another without requiring that the user logs out. Please read the JumpStart section on creating a client/server Service pair to allow user interaction with your service.

6) If you are wanting to support Fast User switching, or are writing your service from scratch, or need to be able to run the service under Windows Vista and later, then you should implement your product as follows:
a) A server which does all the hard work, runs the whole time and has no GUI, and
b) A client which talks to the server, has the GUI and can have one client running for each Fast User Switched users.
The client and server can share data via any kind of inter-process communication (e.g. TCP/IP (We recommend NetTalk), RPC, Named Pipes).

7) Windows Vista, Services and Logins
Even when logged in as Administrator, Windows Vista use UAC (User Account Control). This means that the administrator is a normal user most of the time, except when prompted by Windows for elevated privileges, which allows them to perform an admin option. This is because the authentication token is actually split in two, so when logged in as an administrator you use a user level token until a task requires administrative access, in which case Vista will prompt the user and allow them to choose whether or not the elevate privileges for a specific task.

Unfortunately the implementation of UAC is not consistent. There are tasks that required administrative access (such as installing, starting and stopping a service), where UAC is not implemented. This means that in order to perform the task you need to administrative privileges, but in order to get those privileges you need UAC to elevate you, which isn't implemented. Hence there are things in Vista which you simply cannot do with UAC turned on, unless the user does them manually, and MS has no mechanism for your program to inform the OS that it is going to do something that required privilege elevation.

There are three options to solve this problem:

  1. Right click on the exe or shortcut and start it as administrator.
  2. Go into the User control panel and untick the UAC box.
  3. Create a separate EXE that Starts, Install, Stops and Uninstalls the service. When these functions are needed call this EXE using ShellExecute and start it as an administrator. We will be working on implementing this is future version of Self Service, so it is possible to do without having to write large amounts of additional code. This approach has the advantage that it works regardless of the UAC setting and does not require the user to right click and start the management program as an administrator. It also fits in with the manner in which Microsoft specify that services should work, and adheres to the Vista Certification requirements.


SelfService Global Extension

Global Extension
 

Disable All SelfService Features: removes template generated SelfService code from your app.

 

 

Service Name: This is the service name (no spaces allowed). You can use this name in a DOS prompt to call:
Net Start <ServiceName>
Net Stop <ServiceName>

Use quotes, or use a variable (which you can set in the  'SelfService - Initialize variables' global embed point).

Service Display Name: This is the name displayed in the Windows Service Manager. Use quotes, or use a variable (which you can set in the  'SelfService - Initialize variables' global embed point).

Service Description
: This is the description of your service and is displayed in the Windows Service Manager in Windows 2000,  Windows XP, Windows Server 2003 and Windows Vista. Use quotes, or use a variable (which you can set in the  'SelfService - Initialize variables' global embed point).

Allow command line usage
: Allows you to run your app with /iss (Install and Start Service),  /is (Install Service) or /rs (Remove Service).
Additionally you can add /silent if you do not wish to see the status messages.
See the Command Line Switch Options if you want to customize the command line switches.

Always make Path the same as the EXE folder: This option will set the path of a service to the same as the exe folder location. This is useful as when a service is started by the Service manager, the path is Windows\System32, which is probably not where your data is stored. So it's best to have this option turned on.

Only allow One Instance to run at a time: Will allow only one copy of the application to be run at a time (either as a normal exe or a service)

Service Installation Options: This is where you can choose which user the service should be run as. This is described in the Ground Rules section. (Please note the user account you choose must have a password (it won't work without one)).

Interact With Desktop (does nothing in Vista)
: Allows the Service to display your Graphical User Interface (GUI) to the user, otherwise they are hidden.

Single Dependency: This allows you to add one dependency for your service. This must be the ServiceName of the dependent service. (Should you wish to add multiple dependencies then please see DependenciesQueue)


Turn on logging: Outputs log information to the system debugger. You can either use the default clarion debugger, or preferably use the free DebugView from www.sysinternals.com

Work with WinEvent
: This should be ticked on if you are using WinEvent.

Use Dictionary.Construct/Destruct Fix
: This option makes SelfService work with the Dictionary Class in Clarion 6.1 and above. Clarion 6.0 users may want to turn this option off.



Show Advanced Class Options: This option will display the Advanced Class Tabs. The default settings in the Advanced tabs work perfectly. But we included them in case you want to override any of the class behaviour.



 

     

 

Control Templates

SelfService ships with two Control Templates that make it easy to add buttons to your window that allow you to install (and start) your application as a Service.

Here's what these control templates will add to your window:
 


SelfServiceControls - SelfService - Service Button Controls

 


SelfServiceINstallAndStartButtonControl - SelfService - Install And Start Button Control

How to add these control templates:

Step One: Add the WinEvent and SelfService Global Extension to your window. Configure the name and description of your service. See the Jump Start for a step-by-step guide.

Step Two: Open the window in the Clarion IDE and choose the Populate menu | Control Template | Scroll down the Class SelfService (if it's not there then you didn't add the Global Extension - or you are already using all the SelfService Control Templates) - then choose either:
SelfServiceControls - SelfService - Service Button Controls
or
SelfServiceINstallAndStartButtonControl - SelfService - Install And Start Button Control
 

Tip 1: You can hide any buttons or controls that you don't want displayed in your application. You can also resize and move the controls about.

Tip 2: If you want to call any of these options from a menu item you can call them by adding the following embed code (for example calling the InstallButton):
post (event:accepted, ?InstallButton)
 

SelfService Object Properties

All the common and most useful SelfService settings are configurable via the SelfService Template options. But we've also listed the object properties here. It's more than likely that only advanced programmers will want to access these properties.

AllowCommandLine byte Set in global template - Allows the /is and /rs to install / remove the services.
AllowOnlyOneInstance byte Set in template.
AmService byte Automatically set. Set to 1 if application is being run (started) as a service, otherwise 0.
Automatic byte Defaults to 1 in Construct, this indicates the type of service (automatic or manual).
DependenciesQueue SSDependenciesQueueType Set by template for one single dependency. This must be the ServiceName(s) of the Service(s) that your service is dependent on. This could be your SQL Server service for example.

To add multiple dependencies you could use the following code:
free (gSelfService.DependenciesQueue)
gSelfService.DependenciesQueue.DependencyName = 'Themes'
! XP Themes
add (gSelfService.DependenciesQueue)
gSelfService.DependenciesQueue.DependencyName = 'W32Time'
! Windows Time Maintainer
add (gSelfService.DependenciesQueue)
 
Description cstring(256) Set by template. Used in Install/Remove - the description that is displayed in the Windows Service Controller
DisplayName cstring(256) Set by template. Used in Install/Remove - the name that is displayed in the Windows Service Controller
ErrorString string(1024) Stores the last error - only reported by .InstallService() and .RemoveService()
Executable cstring(256) Automatically generated. This is the full path to the executable. Used in Install/Remove
FirstInstance byte Automatically set. Set to 1 if this is the first instance running on this machine. Will only work if self.NoMutex = 0
InstallAsUserName cstring(80) Set in template, but you can change before you call InstallService. If blank it will use the Local Service account, otherwise specify a user e.g. '.\Jono'. See Ground Rules.
InstallAsPassword cstring(80) See InstallAsUserName
InstallAndStartSwitch string(80) Set in Template. Defaults to '/iss' - switch for Install And Start Service.
InstallSwitch string(80) Set in Template. Defaults to '/is' - switch for Install Service.
InteractWithDesktop byte Set in global template, but you can change this in your code. See Ground Rules.
LoadGroupOrder CString (256) LoadGroupOrder. Used for bulding Kernel Services to specify when the service should be loaded. Normally this will be left blank.
 
LoggingOn byte Set in Template. 0 = no logging, 1 = logging to DebugView (www.sysinternals.com)
NoMutex byte Ability to turn off mutex (1). defaults to 0 (allow mutex)
RemoveSwitch string(80) Set in Template. Defaults to '/rs' - switch for Remove Service
ServiceName cstring(256) Set by template. Used in Install/Remove, and call to StartServiceCtrlDispatcher
SetPathToExeFolder byte Set in template.
ShowErrors byte 0 = no message statements, 1 = show error statements
SilentSwitch string(80) Set in Template. Defaults to '/silent' - switch for Silent Mode - ie no messages
SleepMilliSeconds long If > 0 it will cause the service to sleep this period of time on starting as a service, before launching the global application code - see in _ServiceMain(). You'll have to set this in your own construct method.


SelfService Object Methods

All the common and most useful SelfService settings are configurable via the SelfService Template options. But we've also listed some of the object methods here.

InstallAndStartService (byte p_Silent=1),long,proc This method will install your application as a service with the windows service manager and then it starts the application as a service. Returns 0 on success.
This method can also be used to updated your Service settings with the Windows Service Manager.
InstallService (byte p_Silent=1),long,proc This method will install your application as a service with the windows service manager. Returns 0 on success.
This method can also be used to updated your Service settings with the Windows Service Manager.
RemoveService (byte p_Silent=1),long,proc This method will remove your application as a service from the windows service manager. Returns 0 on success. After calling this function you will need to close your application before you can call InstallService().
ReStartService (byte p_Silent=1),long,proc This method will restart or start your application as a service. Returns 0 on success.
LoadWindowsServiceManager ( ),long,proc This method loads the Windows Service Manager. Works in NT, 2000, XP, 2003 and Vista.
MapDrive (string p_DriveName, string p_RemoteName, string p_UserName, string p_Password),long,proc
 

This method will map a network shared folder to a drive letter. For example to map \\penguin\l-drive to Y: call:
gSelfService.MapDrive ('Y:', '\\penguin\y-drive', '', '')
which will map it using the current user.
Returns 0 on success.

If the return value is non zero you can use the ._WinError() method in order to get the API error message associate with the error code. Below are a list of possible return values if an error occurs.

Return code Description
ERROR_ACCESS_DENIED (5) The caller does not have access to the network resource.
ERROR_ALREADY_ASSIGNED (85) The local device specified by the p_DriveName member is already connected to a network resource.
ERROR_BAD_DEV_TYPE (66) The type of local device and the type of network resource do not match.
ERROR_BAD_DEVICE (1200) The value specified by p_DriveName is invalid.
ERROR_BAD_NET_NAME (67) The value specified by the p_RemoteName member is not acceptable to any network resource provider, either because the resource name is invalid, or because the named resource cannot be located.
ERROR_BAD_PROFILE (1206) The user profile is in an incorrect format.
ERROR_BAD_PROVIDER (1204) The value specified by the internal lpProvider member does not match any provider. Please contact CapeSoft Support if you get this error.
ERROR_BUSY (142) The router or provider is busy, possibly initializing. The caller should retry. This is a not an error code that should be returned by MapDrive.
ERROR_CANCELLED (1223) The attempt to make the connection was cancelled by the user through a dialog box from one of the network resource providers, or by a called resource. This is a not an error code that should be returned by MapDrive.
ERROR_CANNOT_OPEN_PROFILE (1205) The system is unable to open the user profile to process persistent connections.
ERROR_DEVICE_ALREADY_REMEMBERED (1202) An entry for the device specified by p_DriveName is already in the user profile.
ERROR_EXTENDED_ERROR (1208) A network-specific error occurred. (The WNetGetLastError API function can obtain a description of the error).
ERROR_INVALID_PASSWORD (1216) The specified password is invalid and the CONNECT_INTERACTIVE flag is not set.
ERROR_NO_NET_OR_BAD_PATH (1203) The operation cannot be performed because a network component is not started or because a specified name cannot be used.
ERROR_NO_NETWORK (1222) The network is unavailable.

Advanced Methods:
It's more than likely that only advanced programmers will want to access these methods.

CheckCommandLine ( ),long,proc Advanced programmers may want to override this method, which looks for the /is etc. Command line switches.
HandleStopShutdown (long p_ControlType),long Advanced programmers may want to override this method, which is called when either a Service STOP or SHUTDOWN message are sent to the service. If you return 0 then the normal Shutdown code will report back to the SCM that a STOP_PENDING command, and then call .CloseDown. If you return 1 then you must talk to the SCM in your new code.
ManageInstances ( ),long Advanced programmers may want to override this method, which manages the instances of this application using a mutex.
SessionChanged (ulong p_EventType, long p_TSID, long p_Context) Advanced programmers may want to override this virtual notification method, which is called when SessionChange information is available.
WarnAboutOtherInstance () Advanced programmers may want to override this method which is called when multiple instances occur and the settings have been configured to warn the user.
CloseDown ( ) Advanced programmers may want to override this method which at the moment posts an event:closedown to the main thread. This method is called if the Service Manager issues either a STOP (Service must stop) or SHUTDOWN (machine is shutting down) command.


FAQ

I'm getting Compile Errors

SelfService - Introductory Questions

Operating Services

Runtime Problems

Miscellaneous


A1) What operating systems can I run Services on?

Answer: Windows Vista, Windows Server 2003, Windows XP, Windows 2000 and Windows NT 4. Your executables, will still however run on Windows 9x, but just not as a service.


A2) What's the difference between SelfService and running my application from the Scheduled Tasks?

Answer: Firstly, let me say that there aren't any hard fast rules, but here are some points that you may want to weight up when comparing Scheduled applications vs Services:

NT/XP/2000/2003 Scheduler:
1) You either need to add your application to the Scheduled Tasks list manually or find the API calls to do it yourself. Sometimes this works really well, and other times it's a right well pain.
2) If you want to run your app under XP/Vista, the user that you use in the Scheduler needs to have a password. You may get it to work sometimes without, but to prevent it from haunting you this is a better idea. This now means that user has to type in a password if they manually log in.
3) If you choose to start on "Log In", you're no better off than just poking the application into the StartUp folder (which for some applications works pretty well too).
4) If you choose to start your application "at System Startup", then you can't see any windows, which is fine for some apps, but not for all.
5) You must make sure that the Task Scheduler has not been turned off, otherwise your app won't load.
6) I don't know of any tools that do this all for you, so each programmer has to learn the ropes of the NT Scheduler for himself.
7) Explaining to clients that your app runs in the Task Scheduler doesn't quite have the same prestige as saying it can run as a Service <g>.

NT/XP/2000/2003 Services:
1) SelfService provides you with either a command line option to install your application as a Service, or a your application can programmatically install itself as a service via a method call.
2) You don't need a password to install an app as a service as it can use the Local System account.
3) n/a
4) You can still interact with the GUI if you wish. (using the Interact with Desktop option).
5) n/a
6) SelfService does all the hard work for you and comes with full documentation, example, support etc.
7) Services are cool. <g>.


A3) What's the difference between SelfService and Vince Sorensen's ABCFree NT_SVR template?

Answer: We've been working with Vince (ABCFree Author) on this project. So there are a number of similarities.

ABCFree is a fantastic product, and there are a number of Clarion programmers (ourselves included), who have benefited greatly from Vince's product. (Well done Vince).

Here's a little snippet from the ABCFree changes log
---------
Changes 11/9/2003
...
- Added AttachThreadToClarion calls to "NT Service"
  template. This provides support for C5.5 and
  Clarion 5 application migration, but it is
  recommended that the new Capesoft commercial
  template be used instead. (www.capesoft.com)
--------

One of the main reasons for creating the SelfService product was so that there was a commercially Supported service product. i.e. People could request support.

The SelfService product, comes bundled with full documentation, examples and a jump start example. And there is information about service enabling your application, as well as FAQs etc.

There are a couple of things that we have done differently. Some of the changes include:


B1) How can I install and/or remove my application as a Service?

Answer: You can either call the gSelfService.InstallService() or gSelfService.RemoveService() methods, or you can run the application with the /is (install server) or /rs (remove service). Additionally run the application with /silent if you do not want to see the error messages displayed. (Make sure you've ticked on the command line (/is and /rs) option in the Global SelfService Template).

Should you wish to you can change these command line parameters anything you fancy (for example /install). This can be done in the Global Extension.


B2) How can I Start and Stop my Services?

Answer: You can start and stop your applications from the Windows Service Manager.

To load the Windows Service Manage in 2000/XP/2003
Go to Computer Management and expand the "Services and Applications" icon or
Type services.msc in the Start | Run dialogue box.

To load the Windows Service Manager in Windows NT
Go to the Control panel and click on Services.



Alternatively, you can also call Net Start <ServiceName> or Net Stop <Service Name> from a command prompt.
e.g. Net Start CapeSoftJumpStart

If your Service is installed with the Service Manager and is set to start automatically you can also reboot your computer and your service will start.


B3) If I call gSelfService.RemoveService() and then try and Install it again, I get error 1072.

Answer: You need to close your application after calling gSelfService.RemoveService(), before you can Install it again. This is a Windows Service limitation. See also FAQ A3.


B4) In the Windows Service Manager, I get a "The specified service has been marked for deletion".

Answer: You need to close your application after calling gSelfService.RemoveService(), before you can Install it again. This is a Windows Service limitation. See also FAQ A2.


B5) Is there a method where I can control the service from another program?

Answer: Yes there is:

The following methods should help you in performing the various operations:

StartService PROCEDURE (string p_ServiceName, long p_Silent=1),long,proc ,VIRTUAL 
RestartService PROCEDURE (long p_Silent=1),long,proc ,VIRTUAL 
StopService PROCEDURE (string p_ServiceName, long p_Silent=1),long,proc ,VIRTUAL 
GetServiceStatus PROCEDURE (string p_ServiceName, *SS_SERVICE_STATUS p_ServiceStatus, long p_Silent=1),long,proc ,VIRTUAL


C1) I sometimes get a 15 second delay when starting my application, even though I am just running the exe.

Answer: One of the Windows functions sometimes waits for 15 seconds before giving back control to your application. In version 1.10 some code was added to detect if the service was started in the same folder as the exe, if it was it was assumed to be a normal executable (not a service) and the service code was not executed. If you have to start your application in a folder other than the one that the exe is in, then run your application with a /exe to tell SelfService not to call the Service code, when it is started by the user from say a shortcut.


C2) I can't get the Task Tray Icon to work, when the application is loaded as a Service on boot up.

Note: Services are not permitted to interact with the desktop in windows vista, so you will need to create an application that interacts with your service that can display windows, and the icon in the task tray. You can add this app to the start up items so that the interactive app starts when a user logs in.

Answer:
a)
Please make sure you are using WinEvent v3.35 or later.
b) If you turn off the "Interact with Desktop" option in the SelfService Template, the service won't have a taskbar icon.
c) If you turn off the "Allow service to interact with desktop" option in the Windows Service Manager, the service won't have a taskbar icon.
d) If you don't run the service as "Local System" in either the template or the Windows Service Manager, the service won't have a taskbar icon.
e) You can't access the Taskbar icon if you are using Remote Desktop. It's unfortunately one of the limitations of using Remote Desktop.
f) Your window (with the taskbar icon) needs a timer on it
g) You need to use a IconHandle (long) in the Settings tab of the of the WinEvent: Add Icon to System Tray window extension.
h) If you are not using an internal icon (~MyIcon.ico) then you need to make sure that your icon is shipped with the application.


C3) After windows installs updates and re-boots, my application is running, but no longer displays an icon in the tray.

Answer: If you are using WinEvent this is very easy to fix.

1) Make sure you are using the latest builds of SelfService & WinEvent

2) In the WinEvent TaskBarIcon window extension (that adds the TaskBar Icon to your window), make sure you've specified a Handle Variable (see the bits in bold in the template). You can just add a local data item for example:

MyHandle      LONG

WinEvent will also add a timer to your window if you didn't have one. With the Handle variable and the timer, WinEvent is then able to control and update the icon for you.

If all else fails - you can look at the code in the SelfService JumpStart example that ships in your Clarion\3rdParty\Examples folder - as this works 100%.


C4) My Multi-DLL application runs as an application, but not as a service.

Answer: Make sure that all application DLLs are being shipped in the application folder. This is most likely the case of the problem.


C5) I cannot connect to my SQL backend when my app is compiled as a service.

Answer:

Could be a number of different things, so let's take one step at a time:
1. If the Server is on the same machine as your application, you can make the it dependant on the SQL Server service. (dependencies can be entered in the Global Extension template).
2. Are you connecting using a DSN? Make sure that it is a System DSN, not a user DSN.
3. For Services, the service operates independently of the path() ( which is not configured outside of the "logged in" mode), so make sure that your INI settings file (e.g. that FM3 uses) is in your application directory and that the it uses that INI file.
 

D1) How do I manage the one instance of the Service that is already running.

Answer: See the Ground Rules for more information and tips.


D2) Is it possible to add a command line option when the application has been started as a service, so that I can change some of the wording on the window?

Answer: Services can have Command line parameters, which you can customise when the service is stopped in the Windows Service Manager (see how to load the Windows Service Manager)
 


D3) Can I control other Services from within my application?

Answer: You can use the gSelfService.StartService PROCEDURE  (string p_ServiceName, long p_Silent=1) and specify the ServiceName in the parameter. This will start the other services.


D4) How can I install my application as a Service upon installation?

Answer: The easiest way to do this, is to get your installer to run your application with the command line parameter /is. Note: you must have allowed command line usage in the SelfService global extension template.


D5) I'm having problems with my application running in windows Vista.

Answer: Services are not permitted to interact with the desktop in windows vista, so you will need to create an application that interacts with your service that can display windows, and the icon in the task tray. You can add this app to the start up items so that the interactive app starts when a user logs in.


Compile Errors associated with SelfService

Occasionally the template registry gets confused, and does not declare the SelfService classes, which will manifest itself with this error. You need to:

  1. Close the Clarion IDE.
  2. Delete the clarion\template\Registry.trf file.
  3. Open the Clarion IDE, and register your templates:


Support

Your questions, comments and suggestions are welcome.
Keep an eye on our web page (www.capesoft.com) for new versions.
You can also contact us in one of the following ways:

CapeSoft Support
  Web Support Page www.capesoft.com/support/index.htm
 
Email support@capesoft.com
Telephone +27 21 715 4000
Fax +27 21 715 2535
Address PO Box 511, Plumstead, 7801, Cape Town, South Africa
     


Purchasing SelfService

While SelfService is on sale for $149.00. It is available from:

Buy Online
 

Purchase CapeSoft SelfService for $149.00 from:

Buy now at ClarionShop
www.clarionshop.com 
 
     


CapeSoft Sales
  Web www.capesoft.com  
Email sales@capesoft.com
Telephone +27 21 715 4000
Fax +27 21 715 2535
Address PO Box 511, Plumstead, 7801, Cape Town, South Africa
     

Distribution

CapeSoft SelfService ships as pure Clarion source code, so you can simply compile and ship your application. No external resources are necessary for SelfService.


License & Copyright

This product is copyright 2003-2006 by CapeSoft Software (Pty) Ltd.

You are not allowed to copy any of the files, including but not limited to, Template (TPL & TPW) files, SelfService.clw, SelfService.inc and documentation files.

Each developer needs his own license to use SelfService. (Need to buy more licenses?)

This product is provided as-is. CapeSoft Software (Pty) Ltd (trading as CapeSoft), employees of CapeSoft, and Dealers of CapeSoft products, explicitly accept no liability for any loss or damages which may occur from using this package. Use of this package constitutes agreement with this license. This package is used entirely at your own risk.

Credits:
Many thanks to Vince Sorensen, firstly for his ABCFree templates that he makes available to Clarion programmers for free, and secondly for his help and support in this project.


 Version History

Version 3.18 Gold (21 September 2007)

Version 3.17 Gold (19 September 2007)

Version 3.16 Gold (31 August 2007)

Version 3.15 Gold (25 October 2006)

Version 3.14 Gold (24 July 2006)

Version 3.13 Gold (12 July 2006)

Version 3.12 Gold (7 June 2006)

Version 3.11 Gold (5 June 2006)

Version 3.10 Gold (18 May 2006)

Version 3.09 Gold (10 May 2006)

Version 3.08 Gold (1 May 2006)

Version 3.07 Gold (24 April 2006)

Version 3.06 Gold (13 April 2006)

Version 3.05 Gold (12 April 2006)

Version 3.04 Gold (10 April 2006)

Version 3.03 Gold (22 March 2006)

Version 3.02 Gold (16 March 2006)

Version 3.01 Gold (1 March 2006)

Version 3.00 Gold (27 February 2006)

Version 2.05 Gold (10 May 2005)

Version 2.04 Gold (15 November 2004)

Version 2.03 Gold (26 October 2004)

Version 2.02 Gold (13 September 2004)

Version 2.01 Gold (7 September 2004)

Version 2.00 Gold (3 September 2004)

Version 1.12 Beta (23 July 2004)

Version 1.11 Beta (23 January 2004)

Version 1.10 Beta (20 January 2004)

Version 1.03 Beta (18 December 2003)

Version 1.02 Beta (21 November 2003)


Important Notice
: If you upgrading from from v1.01 or v1.00 please read ensure you read
the Version History for v1.02 otherwise you will get compile errors.
 

Version 1.01 Beta (18 November 2003)

Version 1.00 Beta (17 November 2003)



[End of document]