Jump to content

Resolu [VB.NET] Récupérer nom instance service


Recommended Posts

Bonjour,

j'ai une petite question,

j'ai créé un service en VB.NET qui est multi instance en suivant cette page: http://www.codeproject.com/dotnet/ScriptedServiceInstall.asp

Est-il possible de récupérer le nom de l'instance du service qui tourne pour les messages de l'event viewer par exemple ?

Merci

Salut,

je ne comprends pas vraiment la question , normalement le nom du service est une propriété du service, donc à priori tu le connais.

Sinon pour connaitre la liste des services qui tourne avec toutes les infos possible, en .Net , il y a une méthode : System.ServiceController.GetServices()

Je ne sais si ça repond à ta question.

Peut etre tu pourrais nous éclairer.

Link to comment
Share on other sites

En fait j'ai mon service, par exemple, service1.vb:

Public Class Service1

Protected Overrides Sub OnStart(ByVal args() As String)
	EventLog.WriteEntry("Service démarré")
End Sub

Protected Overrides Sub OnStop()
	EventLog.WriteEntry("Service arrété")
End Sub

End Class

et service1.designer.vb:

Imports System.ServiceProcess

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Service1
Inherits System.ServiceProcess.ServiceBase

'UserService overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
	If disposing AndAlso components IsNot Nothing Then
		components.Dispose()
	End If
	MyBase.Dispose(disposing)
End Sub

' The main entry point for the process
<MTAThread()> _
<System.Diagnostics.DebuggerNonUserCode()> _
Shared Sub Main()
	Dim ServicesToRun() As System.ServiceProcess.ServiceBase

	' More than one NT Service may run within the same process. To add
	' another service to this process, change the following line to
	' create a second service object. For example,
	'
	'   ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
	'
	ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}

	System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End Sub

'Required by the Component Designer
Private components As System.ComponentModel.IContainer

' NOTE: The following procedure is required by the Component Designer
' It can be modified using the Component Designer.  
' Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
	components = New System.ComponentModel.Container()
	Me.ServiceName = "Service1"
End Sub

End Class

J'ai ajouté à ce service un class ProjectInstaller.VB pour pouvoir faire du multiinstance:

Imports System.Collections
Imports System.ComponentModel
Imports System.Configuration.Install
Imports System.Collections.Specialized
Imports System.ServiceProcess
Imports Microsoft.Win32

<RunInstaller(True)> _
Public Class ScriptedInstaller
Inherits Installer

'This is a custom project installer.
'Applies a unique name to the service using the /name switch.
'Sets user name and password using the /user and /password switches.
'Allows the use of a local account using the /account switch.

Private Const mServiceName As String = "MonitoredServiceExample"
Private Const mServiceDescription As String = "MonitoredServiceExample"

Private mServiceInstaller As ServiceInstaller
Private mProcessInstaller As ServiceProcessInstaller

Public Sub New()

	mServiceInstaller = New ServiceInstaller
	mProcessInstaller = New ServiceProcessInstaller
	mProcessInstaller.Account = System.ServiceProcess.ServiceAccount.User
	With mServiceInstaller
		.StartType = ServiceStartMode.Manual
		.ServiceName = mServiceName
	End With
	Installers.Add(mServiceInstaller)
	Installers.Add(mProcessInstaller)

End Sub

Public Function GetContextParameter(ByVal Key As String) As String

	Dim sValue As String

	Try
		sValue = Me.Context.Parameters(Key).ToString
	Catch ex As Exception
		sValue = ""
	End Try
	Return sValue

End Function

Protected Overrides Sub OnBeforeInstall(ByVal SavedState As IDictionary)

	'This method is run before the install process.
	'This method is overriden to set the following parameters:
	'	service name (/name switch)
	'	account type (/account switch)
	'	for a user account user name (/user switch)
	'	for a user account password (/password switch)
	'Note that when using a user account, if the user name or password is not set,
	'the installing user is prompted for the credentials to use.

	Dim bIsUserAccount As Boolean = False
	Dim sName As String = ""
	Dim sAcct As String = ""
	Dim sUsername As String = ""
	Dim sPassword As String = ""

	MyBase.OnBeforeInstall(SavedState)
	'Decode the command line switches
	sName = GetContextParameter("name")
	mServiceInstaller.ServiceName = sName

	'What type of credentials to use to run the service
	'The default is User
	sAcct = GetContextParameter("account")
	If sAcct.Length = 0 Then
		sAcct = "user"
	End If
	'Decode the type of account to use
	Select Case sAcct
		Case "user"
			mProcessInstaller.Account = ServiceAccount.User
			bIsUserAccount = True
		Case "localservice"
			mProcessInstaller.Account = ServiceAccount.LocalService
		Case "localsystem"
			mProcessInstaller.Account = ServiceAccount.LocalSystem
		Case "networkservice"
			mProcessInstaller.Account = ServiceAccount.NetworkService
		Case Else
			mProcessInstaller.Account = ServiceAccount.User
			bIsUserAccount = True
	End Select

	'User name and password
	sUsername = GetContextParameter("user")
	sPassword = GetContextParameter("password")

	'Should I use a user account?
	If bIsUserAccount Then
		'If we need to use a user account, set the user name and password()
		mProcessInstaller.Username = sUsername
		mProcessInstaller.Password = sPassword
	End If

End Sub

Public Overrides Sub Install(ByVal StateServer As IDictionary)

	'Modify the registry to install the new service

	Dim rkSystem As RegistryKey
	'HKEY_LOCAL_MACHINE\Services\CurrentControlSet
	Dim rkCurrentControlSet As RegistryKey
	'...\Services
	Dim rkServices As RegistryKey
	'...\<Service Name>
	Dim rkService As RegistryKey
	'...\Parameters - this is where you can put service-specific Configuration()
	Dim rkConfig As RegistryKey
	Dim sImagePath As String = ""

	MyBase.Install(StateServer)
	'Define the registry keys
	'Navigate to services
	rkSystem = Registry.LocalMachine.OpenSubKey("System")
	rkCurrentControlSet = rkSystem.OpenSubKey("CurrentControlSet")
	rkServices = rkCurrentControlSet.OpenSubKey("Services")
	'Add the service
	rkService = rkServices.OpenSubKey(mServiceInstaller.ServiceName, True)
	'Default service description
	rkService.SetValue("Description", mServiceDescription)
	'Display the assembly image path and modify to add the service name
	'The executable then strips the name out of the image
	Console.WriteLine("ImagePath: " & CType(rkService.GetValue("ImagePath"), String))
	sImagePath = CType(rkService.GetValue("ImagePath"), String)
	sImagePath &= " -s" & mServiceInstaller.ServiceName
	rkService.SetValue("ImagePath", sImagePath)
	'Create a parameters subkey
	rkConfig = rkService.CreateSubKey("Parameters")
	'Close keys
	rkConfig.Close()
	rkService.Close()
	rkServices.Close()
	rkCurrentControlSet.Close()
	rkSystem.Close()

End Sub

Protected Overrides Sub OnBeforeUninstall(ByVal SavedState As IDictionary)

	'Uninstall based on the service name

	MyBase.OnBeforeUninstall(SavedState)
	'Set the service name based on the command line
	mServiceInstaller.ServiceName = GetContextParameter("name")

End Sub

Public Overrides Sub Uninstall(ByVal StateServer As IDictionary)

	'Modify the registry to remove the service

	Dim rkSystem As RegistryKey
	'HKEY_LOCAL_MACHINE\Services\CurrentControlSet
	Dim rkCurrentControlSet As RegistryKey
	'...\Services
	Dim rkServices As RegistryKey
	'...\<Service Name>
	Dim rkService As RegistryKey
	'...\Parameters - this is where you can put service-specific Configuration()

	MyBase.Uninstall(StateServer)
	'Navigate down the registry path
	rkSystem = Registry.LocalMachine.OpenSubKey("System")
	rkCurrentControlSet = rkSystem.OpenSubKey("CurrentControlSet")
	rkServices = rkCurrentControlSet.OpenSubKey("Services")
	rkService = rkServices.OpenSubKey(mServiceInstaller.ServiceName, True)
	'Remove the parameters key
	rkService.DeleteSubKeyTree("Parameters")
	'Close keys
	rkService.Close()
	rkServices.Close()
	rkCurrentControlSet.Close()
	rkSystem.Close()

End Sub

End Class

Avec un petit script d'installation installutil.bat:

@echo off
set SERVICE_HOME=C:\Documents and Settings\mgh\My Documents\Visual Studio 2005\Projects\InstanceName\InstanceName\bin\Debug
set SERVICE_EXE=InstanceName.exe
REM the following directory is for .NET 1.1, your mileage may vary
set INSTALL_UTIL_HOME=C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
REM Account credentials if the service uses a user account

set PATH=%PATH%;%INSTALL_UTIL_HOME%

cd %SERVICE_HOME%

echo Installing Service...
installutil /name=InstanceName1 /account=localsystem %SERVICE_EXE%
REM installutil /name=InstanceName2 /account=localsystem %SERVICE_EXE%
REM installutil /name=InstanceName3 /account=localsystem %SERVICE_EXE%

echo Done.

Quand je l'installe, j'ai le bon nom de mon instance, à savoir InstanceName1 qui est donné dans mon fichier .bat

Donc dans la liste des services qui tournent, je vois bien ce nom d'instance.

Par contre, une fois que je vais dans event viewer, j'ai le nom "Service1" qui apparait, comme il est spécifié dans le fichier Service1.Designer.vb avec la ligne

	Private Sub InitializeComponent()
	components = New System.ComponentModel.Container()
	Me.ServiceName = "Service1"
End Sub

Au lieu de

Me.ServiceName = "Service1"

, n'est-il pas possible de mettre autre chose qu'un nom fiche, et plutot le nom de mon instance ???

Merci d'avance :)

Link to comment
Share on other sites

  • 1 month later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...