Create service with arguments using SC.exe - windows-services

I've spent the last 2 hours trying every conceivable way to create a service using sc.exe and pass arguments but I can't seem to get it right.
I've read this SO question and all the answers about 5 times and it's been no help!
From what I read there it seems I should construct the command like this:
sc create MyService binPath= "C:\path\to\myservice.exe --param1=TestString"
My Service OnStart method looks like this:
Protected Overrides Sub OnStart(ByVal args() As String)
If Not IsNothing(args) Then
Library.WriteLog("Number of args = " & args.Count)
If args.Count > 0 Then
For i = 0 To args.Count - 1
Library.WriteLog("Arg" & i & ": " & args(i))
Next
End If
End If
End Sub
But everything I've tried yields "Number of Args = 0" in the log
For clarity I've tried the following (plus a few more probably):
sc create MyService binPath= "C:\path\to\myservice.exe --param1=TestString"
sc create MyService binPath= "C:\path\to\myservice.exe --TestString"
sc create MyService binPath= "C:\path\to\myservice.exe --param1=\"TestString\""
sc create MyService binPath= "C:\path\to\myservice.exe -param1=TestString"
sc create MyService binPath= "C:\path\to\myservice.exe -TestString"
sc create MyService binPath= "C:\path\to\myservice.exe -param1=\"TestString\""
I must be missing something really silly here but I'm banging my head off a wall with it!

According to this answer and the comments, the args parameter of OnStart is only used when manually setting start parameters in the windows service dialog, which cannot be saved.
You can use the arguments you are setting up by accessing them in the Main method (located in the Service.Designer.vb file by default). Below is an example:
<MTAThread()> _
<System.Diagnostics.DebuggerNonUserCode()> _
Shared Sub Main(ByVal args As String())
Dim ServicesToRun() As System.ServiceProcess.ServiceBase
ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1(args)}
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End Sub
You will need to add or modify a constructor to your service class to accept the arguments:
Private ReadOnly _arguments As String()
Public Sub New(ByVal args As String())
InitializeComponent()
_arguments = args
End Sub
Then your OnStart method becomes:
Protected Overrides Sub OnStart(ByVal args() As String)
If Not IsNothing(args) Then
Library.WriteLog("Number of args = " & _arguments.Count)
If args.Count > 0 Then
For i = 0 To args.Count - 1
Library.WriteLog("Arg" & i & ": " & _arguments(i))
Next
End If
End If
End Sub

Related

How to make global variables "immutable" in Lua/LuaJ?

Description
I'm doing a LuaJ program, and here's a lib script like this:
function foo()
print("foo");
end
I want the foo function can be invoked in other scripts directly (no require), but performs immutable in different scripts. ( Even a script overrides it, it performs as the original way in other scripts. )
For example, here's the script 1:
foo = function()
print("bar");
end
and here is the script 2:
foo();
What's done
I have saw these two questions. They do work but not the solution to this problem.
LuaJ How to avoid overriding existing entries in Globals table
Preventing Function Overriding in Lua Table
Making global environment access-only (Lua)
I tried loading lib every time exec a script, or set local _ENV, but because there may be further callbacks from Java to Lua, it doesn't work correctly.
I now handle it by create a Globals and load lib script every time load a script in Java like this:
public static void main(String[] args) {
loadAndCallViaDifferentEnv(libPath, script1);
loadAndCallViaDifferentEnv(libPath, script2);
}
static void loadAndCallViaDifferentEnv(String libPath, String scriptPath) {
Globals globals = JsePlatform.standardGlobals();
globals.loadfile(libPath).call();
globals.loadfile(scriptPath).call();
}
It works well, but costs much. Is there a better way?
I assume you want to protect three functions from overwriting: foo1, foo2 and print
-- define foo1 and foo2 inside protected table instead of as usual globals
local protected = {}
function protected.foo1()
print("foo1");
end
function protected.foo2()
print("foo2");
end
-- if a function to be protected already exists, remove it from globals:
protected.print = print
print = nil
-- Now set the metatable on globals
setmetatable(_G, {
__index = protected,
__newindex =
function(t, k, v)
if not protected[k] then
rawset(t, k, v)
end
end
})
Now you can invoke foo1, foo2 and print from other modules without require, but you can not overwrite them:
-- the script 1:
foo1 = function()
print("bar");
end
foo1(); -- original protected.foo1() is invoked
-- the script 2:
foo1(); -- original protected.foo1() is invoked

MicronautTest Datasource setup not clean before each execution

I have this micronaut application doing some basic database lookup, just for testing the framework. I have setup the application with flyway database migrations, running a h2 database in my test setup (production uses postgresql). This is used for setting up the schema correctly.
My repository is created using Micronaut data for jpa, so I do not know how to create it without running the tests in full micronaut context.
In my test I try to insert some data in the setup method, before executing some spock tests. When the setup has run once, I would expect it to start with a clean datasource for the next test execution. Since the data will violate a unique constraint, it fails with an sql error in setup for the second test being run. Here's my code:
#MicronautTest()
class CompanyRepositoryTest extends Specification {
#Inject
CompanyRepository repository
#Inject
DataSource dataSource
def sql
def setup() {
sql = new Sql(dataSource: dataSource)
sql.execute(dataSql)
}
def 'test company creation' () {
given:
def name = 'test2'
def orgNumber = '1232429045'
when:
def company = repository.save(new Company(name: name, organizationNumber: orgNumber))
then:
company.id != null
}
#Unroll
def 'get company for #desc'() {
when:
Company result = repository.find(id)
then:
name == null ? result == null : name == result.name
where:
id | name | desc
1 | 'test1' | 'existing company'
2 | null | 'non-existing company'
}
def dataSql = """
insert into company(name, organization_number) values
('test1', '1232429045');
"""
I guess I could create a cleanup block where I execute delete statements, but I see that as a last resort as I would expect the datasource to be clean before each test run.
After a good nights sleep, the obvious answer came to me. Instead of executing the sql through groovy sql,I use entitymanager. Then this works as expected
#Inject
EntityManager entityManager
def setup() {
entityManager.createNativeQuery(dataSql).executeUpdate();
}

What is the difference between defining variables using def and without?

In relation to Jenkins DSL, what is the difference between:
def cwd = pwd()
and
cwd = pwd()
?
It's a difference of scope. When you assign a value to a variable without a "def" or other type, in a Groovy script, it's added to the "binding", the global variables for the script. That means it can be accessed from all functions within the script. It's a lot like if you had the variable defined at the top of the script.
You could wind up with unexpected behavior if multiple threads are acting on the script.
def a = {
x = 1
println x
}
def b = {
x = 2
println x
}
new Thread(a).start()
new Thread(b).start()
... could produce two ones, two twos, or a mix.
In contrast, using "def" makes a local variable:
def a = {
def x = 1
println x
}
def b = {
def x = 2
println x
}
new Thread(a).start()
new Thread(b).start()
... will always print a 1 and a 2, in arbitrary order.
It's a good question, but it's more a Groovy question.
From what I understand, defining a variable without def keyword will work from a script, but not if you were in a class method. Example from this blog post :
class MyTest {
def testMethod() {
y = 3
println y
}
}
t = new MyTest()
t.testMethod()
Variable t will be defined without problem but y definition will throw an exception.
What it means is that in our context (Jenkins pipeline) you could always define your variable without the def keyword because you are always in a script context and your variables will be bound to the script. However, I think it is good practice to use def keyword because it shows you know when you instantiate your variables, and it also can avoid some problems of duplicate variables definitions (if you define them with the def keyword at least compilation will fail if you defined the same variable twice).
Finally, from Groovy documentation :
When using def in Groovy, the actual type holder is Object (so you can
assign any object to variables defined with def, and return any kind
of object if a method is declared returning def).
So you might want to be specific and specify the type of variable you are defining. In your case you could define cwd as :
String cwd = pwd()
It would forbid you to do things like :
def cwd = pwd()
cwd = 1000 // Valid code
String cwd2 = pwd()
cwd2 = 1000 // Will fail compilation

Using a Grails service inside a script

I'm trying to use a Grails service inside the following Grails script
includeTargets << grailsScript("_GrailsInit")
target(loadGames: "The description of the script goes here!") {
def listFile = new File('list.txt')
listFile.eachLine {
def result = ctx.getBean("bggService").search(it)
println it + " " + result.length()
}
}
setDefaultTarget(loadGames)
I've seen about a dozen different webpages each offering a different combination of ctx appCtx, and applicationContext (as well as many others) as suggestions, however none of them work. Typically they complain that the context variable that I am trying to use does not exist.
Why can't Grails just use services inside a script in exactly the same way that they get used in controllers?
What is the right way to use a Grails service inside a Grails script?
Getting hold of ApplicationContext and grailsApplication is possible though bootstrap command. Include _GrailsBootstrap script, then call configureApp () or depend on it in order to make ApplicationContext available in script:
includeTargets << grailsScript("_GrailsInit")
includeTargets << grailsScript("_GrailsBootstrap")
target(loadGames: "The description of the script goes here!") {
depends(configureApp)
def listFile = new File('list.txt')
listFile.eachLine {
//Once configureApp() called ApplicationContext can be accessed as appCtx
def result = appCtx.getBean("bggService").search(it)
println it + " " + result.length()
}
}
setDefaultTarget(loadGames)

Windows service not executing after first run

I have create a windows service in VS 2010. I install it and also run it at the same time and set startup type to Automatic . I see it running fine through EventViewer and is successfully completed.
But after that i done see EventViewer showing anything, even if the work is doen it still should check DB and skip as all rows done.
So what is the issue ?
DO i need to make it an infinite loop in the service to keep it running?
Something like
While (ROWs in DB ! = null) ?
Because it does not seem it is working like task scheduler!
Yes, you need to do a loop with the possibility to break it again. Example service (VB.NET):
Public Class MyService
Protected Property IsRunning As Boolean = False
Protected Sub OnStart(args() As String)
IsRunning = True
' make the loop function run asynchronously
Dim t As New System.Threading.Thread(AddressOf MyLoopFunction)
t.Start()
End Sub
Protected Sub MyLoopFunction
While IsRunning
' here comes your code ...
' sleep for a second for better CPU freedom
System.Threading.Thread.Sleep(1000)
End While
End Sub
Protected Sub OnStop()
IsRunning = False
End Sub
End Class

Resources