Self Installing Windows Service in vb.net

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I have a windows service in vb.net.<span> I have used the code I have found on the web to self install via the command line, but I cannot get the service started via the command line.<span>
Whenever I run it via the command line, I get the message "Cannot start service from the command line or a debugger.<span>
A windows Service must first be installed (using the installutil.exe) and then started with the SeverExplorer, ...." My code is posted below.
<pre class="prettyprint lang-vb Public Class Service

Public Sub Main(args As String())

Try
Dim path As String = System.Reflection.Assembly.GetExecutingAssembly().Location
Dim commandLine As String() = Nothing
Dim msgText As String = ""
If args.Length > 0 Then
Select Case args(0).ToUpper()
Case "-I"
commandLine = New String() {path}
System.Configuration.Install.ManagedInstallerClass.InstallHelper(New String() {path})
msgText = "Service installed sucessfully! Please start it from the Services control panel."
Case "-U"
commandLine = New String() {"/u", path}
System.Configuration.Install.ManagedInstallerClass.InstallHelper(New String() {"/u", path})
msgText = "Service uninstalled sucessfully!"
Case Else
Throw New ArgumentException("Invalid command line argument.")
End Select
System.Configuration.Install.ManagedInstallerClass.InstallHelper(commandLine)
MsgBox(msgText, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "peShipLS Service Install")
Else
Dim ServicesToRun As System.ServiceProcess.ServiceBase() = New System.ServiceProcess.ServiceBase() {New Service()}
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End If

Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "peShipLS Service Install")
End Try

End Sub

Protected Overrides Sub OnStart(ByVal args() As String)
Add code here to start your service. This method should set things
in motion so your service can do its work.

Timer.Enabled = True
Timer.Interval = 15000 15 second
Timer.Interval = 1800000 30 minutes
Timer.Interval = 3600000 1 hour
Timer.Interval = 86400000 24 hours

End Sub

Protected Overrides Sub OnStop()
Add code here to perform any tear-down necessary to stop your service.

End Sub

Private Sub Timer1_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Timer.Elapsed

Create the source, if it does not already exist.
If Not EventLog.SourceExists("peShipLS") Then
EventLog.CreateEventSource("peShipLS", "peShipLS Log")
End If

Create an EventLog instance and assign its source.
Dim myLog As New EventLog()
myLog.Source = "peShipLS"

Write an informational entry to the event log.
myLog.WriteEntry("Running at: " & CStr(TimeOfDay), EventLogEntryType.Information)

End Sub

End Class[/code]
<br/>

View the full article
 
Back
Top