Jump to content

_Service_UDF v4 : Build your own service with autoit code


arcker
 Share

Recommended Posts

This is untested (by me, but tested in post below), but seems a good direction if you don't want to wait for the next version.

Const $SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 3
Const $tagSERVICE_DELAYED_AUTO_START_INFO = "struct;bool fDelayedAutostart;endstruct"

Func _SERVICE_CONFIG_DELAYED_AUTO_START($hService, $bDelayedAutoStart = True)
    Local $tSERVICE_DELAYED_AUTO_START_INFO = DllStructCreate($tagSERVICE_DELAYED_AUTO_START_INFO)  ;Create DLLStruct from Const definition
    DllStructSetData($tSERVICE_DELAYED_AUTO_START_INFO, "fDelayedAutoStart", $bDelayedAutoStart)    ;Set Struct Bool value to $bDelayedAutoStart parameter value
    $iRtn = _ChangeServiceConfig2($hService, $SERVICE_CONFIG_DELAYED_AUTO_START_INFO, DllStructGetPtr($tSERVICE_DELAYED_AUTO_START_INFO))   ;Call Advapi32 ChangeServiceConfig2 function
    $tSERVICE_DELAYED_AUTO_START_INFO = 0   ;Free struct resources
    Return $iRtn[0] ;Return _ChangeServiceConfig2 function result
EndFunc

Func _ChangeServiceConfig2($hService, $dwInfoLevel, $lpInfo)
    Return DllCall("Advapi32.dll", "int", "ChangeServiceConfig2", "HANDLE", $hService, "DWORD", $dwInfoLevel, "LONG_PTR", $lpInfo)  
EndFunc

 

Edited by spudw2k
Link to comment
Share on other sites

  • 2 weeks later...

@spudw2k

I was testing your function but I am getting an Error return from IsHWnd($hService) in the following line:

 If Not IsHWnd($hService) Then Return SetError(1,0,0)    ;Check if $hService is a real Handle

 My main procedure (a CUI executable is created) is something like:

#include <Services.au3>
#include <ServicesConstants.au3>

Const $SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 3
Const $tagSERVICE_DELAYED_AUTO_START_INFO = "struct;bool fDelayedAutostart;endstruct"

Local $hSC, $hService
$hSC = OpenSCManager("", $SC_MANAGER_CONNECT)
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $hSC = ' & $hSC & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
$hService = OpenService($hSC, "Servicename", $SERVICE_INTERROGATE)
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $hService = ' & $hService & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

$iRC = _SERVICE_CONFIG_DELAYED_AUTO_START($hService, True)

The Debug ConsoleWrite shows that both $hSC and $hService are set to pointers (hexadecinal number returns). The pointer $hService is passed ok to the Function (I have put another Debug write inside).

What am I missing?
 


 

Edited by kschwarz
Link to comment
Share on other sites

Looks like I inappropriately used that function.  It appears to be meant for Window handles and not handles in general which I assumed.  

I wanted to add some error checking, I could not find an immediate replacement for the function.  I guess try removing or commenting out the line.  Hopefully it gets further along/works after that.  Considering the example code you posted, I would think your $hService variable obtains a valid handle for the DLL call in the _SERVICE_CONFIG_DELAYED_AUTO_START function I made.

Let me know how it works.

Link to comment
Share on other sites

@spudw2k

I have removed the "If Not IsHWnd($hService) Then Return SetError(1,0,0)    ;Check if $hService is a real Handle" line and compiled my program again and it worked correctly. See:

"SC qc" before running my program:

[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: MyService
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 4   DISABLED
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\temp\MyService.exe
        LOAD_ORDER_GROUP   : Default
        TAG                : 0
        DISPLAY_NAME       : MyService
        DEPENDENCIES       : NETMAN
        SERVICE_START_NAME : LocalSystem

"SC qc" after my program execution:

[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: MyService
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START  (DELAYED)
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\temp\MyService.exe
        LOAD_ORDER_GROUP   : Default
        TAG                : 0
        DISPLAY_NAME       : MyService
        DEPENDENCIES       : NETMAN
        SERVICE_START_NAME : LocalSystem

When you find a replacement for that line, please let me know. 

Thanks!

Edited by kschwarz
Link to comment
Share on other sites

@kschwarz Glad to see it worked for you.  I ended up simply removing the line and don't plan on finding a replacement for it.  I think it makes most sense to perform the error checking on the OpenService function return and not continue with the script if it has an error.

 

Edited by spudw2k
Link to comment
Share on other sites

  • 2 weeks later...
On ‎11‎.‎09‎.‎2018 at 8:34 PM, DonChunior said:

Is there any reason why this UDF has not yet been added to the "User Defined Functions" wiki page?
Are the other UDFs regarding to services better than this one?

I have to reprimand myself: This UDF is listed in the wiki anyway!
But under "Automation" and not under "Windows", which is probably why I missed it.

Edited by DonChunior
Link to comment
Share on other sites

@water I think @DonChunior have right, are you agree ?

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites


@water did the trick ;) Could you @DonChunior check it again .

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

  • 1 month later...

Hi everybody !

I'm coding a client/server with client starting as service with this great udf but I've got some problem.

I'm using this version from syn5555 (v4 reworked) :

My client works just fine if I don't close windows session. But when I log in or log out, I've got crashes/hang randomly.

I checked all dllcall (threadsafe), put some logprint() to find where it bugs and I can't find where the problem comes from. Windows event viewer just tell me that the .exe crashed and it will be restart.

I can add the client/server code if you need.

Link to comment
Share on other sites

52 minutes ago, tatane said:

I'm coding a client/server with client starting as service with this great udf but I've got some problem.

https://www.autoitscript.com/forum/topic/80201-_service_udf-v4-build-your-own-service-with-autoit-code/?do=findComment&comment=1374529

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Link to comment
Share on other sites

I'm already using the latest version of AutoIt :( with Windows 7.

EDIT : When it stops working and the process still exists, its size in memory goes from 11000K to 1400K.

See attachment for the code of client and server. The client is running as service not the server.

Change the IP address of the server in the _TechTools_Client() function.

clientserver_service.7z

Edited by tatane
Link to comment
Share on other sites

5 hours ago, tatane said:

Should I recode functions like AdlibeRegister() or TimerInit() too ? What kind of functions are concerned ?

I have no clue, but, I think that you can write all as user level executable and if that works, use a service as a watchdog. When you run the service as a watchdog, the "user level" executable, runs with the same permissions as the service. 

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Link to comment
Share on other sites

  • 3 weeks later...

Arcker - Great Job on this!!! It took me a bit to figure out how to get my needs met, but it works great, with one exception. 

 

What my script does:

Creates a UDP socket on a specific port to listen for commands from a client, it then interacts with hyper-v via powershell to manipulate virtual machines.

It works great, until I need to stop the service. The listening code uses a do until loop.

I.E.:

Do
<Insert code here>
Until $my_var <> ""

(once data is recived, the $my_var is no longer empty and the loop exists, performs the powershell commands, then calls the do function again to listen again)

How are the commands to restart or stop the service called? I think if I change my script to :

Do
<insert code here>
Until $my_var <> "" OR <stop command> OR <restart command>

 

Any suggestions?

 

Thanks in advance!

Edited by quantum900
Link to comment
Share on other sites

  • 3 months later...

Hi Guys,

    I need help.
    I created a service in Windows to start every time I reboot the machine.
    At startup the service is returning error: 1053 The service did not respond to the start or control request in a timely manner.
    I want to know if the problem is in the .EXE that I generated or in the service created via AutoIT?

 

include <Services_1.au3>

    If @OSArch = "X64" Then
        $path = "c:\Program Files (x86)\teste"
        DirCreate($path)
    Else
        $path = "c:\Program Files\teste"
        DirCreate($path)
    EndIf


Global $retorno = _Service_Create("Agente.Teste", _
        "Agente - Teste", _
        $SERVICE_WIN32_OWN_PROCESS, _
        $SERVICE_AUTO_START, _
        $SERVICE_ERROR_IGNORE, _
        $path & "\Agente.Teste.exe")
        
MsgBox(0, "$retorno",  $retorno)
MsgBox(0, "@error", @error)

erro.png.24b0bca6ae8697e87c914435efebcfed.png

Tks.

Blois

Edited by Blois
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...